因为我不知道我的问题是如何命名的,所以我不能保证最近或根本没有人问过同样的问题。
我确实注意到了,但是有很多主题具有相似的标题,但它们似乎与我的问题无关。
我有一个自定义列表类,它实现了泛型。
class MyList<T>
{
public void add(T item) // adds an item to the list
{ /* code */ }
public void add(MyList<T> list) // attaches an existing list to the end of the current one
{ /* code */ }
}
我也有类(class):
class Apple : Fruit
和
class Banana : Fruit
现在,是相关代码:
MyList<Fruit> fruitList = new MyList<Fruit>();
// fill fruitList
fruitList.add(new Apple()); // works, of course
fruitList.add(new Banana()); // works as well, of course
MyList<Apple> appleList = new MyList<Apple>();
// fill appleList
fruitList.add(appleList); // doesn't work. Why?
即使 appleList 是一个 MyList(Of Apple) 而 Apple 是 Fruit,当 MyList(Of Fruit) 被询问时,VisualStudio 不接受 MyList(Of Apple) 作为参数。
但是,如果我要这样声明列表:
MyList<object> fruitList = new MyList<object>();
然后一切都恢复正常了。我到底做错了什么?
非常感谢您的回答,感谢您花时间阅读,即使没有回答。
最佳答案
您正在尝试使用 covariance .
.Net 只支持接口(interface)上的泛型变体,所以那行不通。
此外,协变只对不可变类型有意义。
如果可以转换 MyList<Apple>
到 MyList<Fruit>
, 然后你就可以添加 Orange
到列表中,违反了类型安全。
相反,您可以使该方法通用:
public void Add<U>(IList<U> list) where U : T
关于c# - 关于泛型和继承(原谅我不好的标题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9024069/