加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:46:26 所属栏目:百科 来源:网络整理
导读:由于我不知道我的问题如何,所以我不能保证,最近没有人问过同样的问题. 我确实注意到,但是有相当多的线程具有相似的标题,但它们似乎与我的问题无关. 我有一个自定义列表类,它实现泛型. class MyListT{ public void add(T item) // adds an item to the list {
由于我不知道我的问题如何,所以我不能保证,最近没有人问过同样的问题.

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

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

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 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(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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读