c# - 关于泛型和继承(原谅我不好的标题)

标签 c# generics covariance

因为我不知道我的问题是如何命名的,所以我不能保证最近或根本没有人问过同样的问题。

我确实注意到了,但是有很多主题具有相似的标题,但它们似乎与我的问题无关。

我有一个自定义列表类,它实现了泛型。

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/

相关文章:

c# - 不同固件中的协方差导致代码中断?

c# - 对 "Already defines a member with the same parameter types"错误感到困惑

C# 用正则表达式拆分 string.format 字符串

c# - 在具有内存限制的 Docker 容器中运行 .NET Core 应用程序

ios - 从空 Swift 数组中获取对象类型

java - 我想扩展枚举和对象(通用)

C# web api Swagger 集成

c# - 在 ASP.Net MVC 中集中正则表达式验证模式

c# - 如何将数字转换为泛型类型?

java - 继承与列表