c# – 关于泛型和继承(原谅我的坏标题)

c# – 关于泛型和继承(原谅我的坏标题),第1张

概述由于我不知道我的问题如何,所以我不能保证,最近没有人问过同样的问题. 我确实注意到,但是有相当多的线程具有相似的标题,但它们似乎与我的问题无关. 我有一个自定义列表类,它实现泛型. class MyList<T>{ public void add(T item) // adds an item to the list { /* code */ } public void 由于我不知道我的问题如何,所以我不能保证,最近没有人问过同样的问题.

我确实注意到,但是有相当多的线程具有相似的标题,但它们似乎与我的问题无关.

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

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 Apple : Fruit

class Banana : Fruit

现在来了相关代码:

MyList<Fruit> fruitList = new MyList<Fruit>();// fill fruitListfruitList.add(new Apple()); // works,of coursefruitList.add(new Banana()); // works as well,of courseMyList<Apple> appleList = new MyList<Apple>();// fill appleListfruitList.add(appleList); // doesn't work. Why?

即使appleList是MyList(Apple),Apple是Fruit,VisualStudio不接受MyList(Apple)作为参数,当MyList(Of Fruit)被询问时.

但是,如果我要这样声明列表:

MyList<object> fruitList = new MyList<object>();

然后一切都行.我做错了什么?

一个答案将非常感谢,谢谢你花时间阅读,即使没有回答.

解决方法 你试图使用 covariance.
.Net只支持接口上的通用方差,这样就不行了.

另外,协方差只对不变类型有意义.
如果可以转换MyList< Apple>到MyList< Fruit>之后,您就可以在列表中添加一个橙色,违反了类型的安全性.

相反,您可以使该方法通用:

public voID Add<U>(IList<U> List) where U : T
总结

以上是内存溢出为你收集整理的c# – 关于泛型和继承(原谅我的坏标题)全部内容,希望文章能够帮你解决c# – 关于泛型和继承(原谅我的坏标题)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1259689.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存