【问题标题】:Interface with List of same interface具有相同接口列表的接口
【发布时间】:2013-10-31 01:56:39
【问题描述】:

我有如下界面:

public interface IObject{
double x {get;}
double y {get;}
List<IObject> List{get; set;}
}

还有这个类

public class Holder<T> where T : IObject {
private T myItem;
public void ChangeItemList(T item){
myItem.List = item.List;
}

但是编译器不喜欢 ChangeItemList 方法并且在这一行:

myItem.List = item.List;

给我这个错误:

Cannot convert source type 'List<T>' to target type 'List<IObject>'

为什么我不能这样做?对于这种情况有什么好的解决方案? 谢谢你

【问题讨论】:

  • 您不可能拥有该接口,因为接口不能包含字段。此代码无法编译。
  • 您的界面中似乎有成员字段。这是不允许的。双x;和双 y;不能在接口中声明。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 对不起,它们应该是属性。我编辑了我的代码。
  • 为什么不:public void ChangeItemList(IObject item)?

标签: c# .net interface


【解决方案1】:

我不确定您想要实现什么,但以下编译和运行无一例外:

class Program
{
    static void Main(string[] args)
    {
        var holder = new Holder<IObject>();
        holder.MyItem = new Object { List = new List<IObject>() };
        holder.ChangeItemList(new Object { List = new List<IObject>() });
    }
}

public class Object : IObject
{
    public List<IObject> List { get; set; }
}

public interface IObject
{
    List<IObject> List { get; set; }
}

public class Holder<T> where T : IObject
{
    public T MyItem { get; set; }

    public void ChangeItemList(T item)
    {
        MyItem.List = item.List;
    }
}

【讨论】:

    【解决方案2】:

    试着做这件事——对我有用。我遇到的问题是 myItem 为空。

    public class Holder<T> where T : IObject
    {
        private T myItem = Activator.CreateInstance<T>();
    
        public void ChangeItemList(T item)
        {
            myItem.List = item.List;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 2011-11-30
      • 2011-11-23
      • 2015-01-25
      • 1970-01-01
      相关资源
      最近更新 更多