我有以下接口:
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方法,并在此行:
However the compiler doesn't like the ChangeItemList method and on this line :
myItem.List = item.List;
给我这个错误:
gives me this error:
Cannot convert source type 'List<T>' to target type 'List<IObject>'
为什么我不能做到这一点,什么是对于这种情况好的解决办法? 谢谢
Why can't I do it and what is a good solution for this scenario? thank you
我不知道你想达到什么,但下面的编译和运行没有异常:
I am not sure what you want to achieve but the following compiles and runs without exceptions:
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;
}
}