I have the following interface:
我有以下界面:
public interface IObject{
double x {get;}
double y {get;}
List<IObject> List{get; set;}
}
and this class
和这堂课
public class Holder<T> where T : IObject {
private T myItem;
public void ChangeItemList(T item){
myItem.List = item.List;
}
However the compiler doesn't like the ChangeItemList method and on this line :
但是编译器不喜欢ChangeItemList方法并且在这一行:
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
为什么我不能这样做,这个场景有什么好的解决方案?谢谢
2 个解决方案
#1
0
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;
}
}
#2
0
Try to do this one- worked for me. The problem i had that myItem was null.
尝试这样做 - 为我工作。我的问题是myItem为null。
public class Holder<T> where T : IObject
{
private T myItem = Activator.CreateInstance<T>();
public void ChangeItemList(T item)
{
myItem.List = item.List;
}
}
#1
0
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;
}
}
#2
0
Try to do this one- worked for me. The problem i had that myItem was null.
尝试这样做 - 为我工作。我的问题是myItem为null。
public class Holder<T> where T : IObject
{
private T myItem = Activator.CreateInstance<T>();
public void ChangeItemList(T item)
{
myItem.List = item.List;
}
}