协方差不适用于列表< T> [英] Covariance Doesnt Work For List<T>

查看:91
本文介绍了协方差不适用于列表< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





今天我研究了C#中的Co-Variance。我试图实现一个样本。



适用于IEnumerable< t>。



Hi,

Today I Studied about Co-Variance in C#. And I tried to implement a sample.

It works for IEnumerable<t>.

IEnumerable<string> objInt = new List<string>();
            IEnumerable<object> obj = objInt;



但是当我尝试使用List或IList时,它无效。

有人可以清楚地解释一下这个原因吗?




But when I try with List or IList, It is not working.
Can someone clearly explain me on this why?

IList<string> objInt2 = new List<string>();
           IList<object> obj2 = objInt2;





上述代码无法使用



添加了代码块 - OriginalGriff [/ edit]



The above code is not working

[edit]Code block added - OriginalGriff[/edit]

推荐答案

问题是您将List向上转换为支持Add方法和索引的类型Setter(仅与Getter相对)。

这意味着你可以这样写:

The problem is that you are upcasting the List to a type which supports both an Add method, and a index Setter (as opposed to a Getter only).
Which means that you could write this:
List<Dog> dogs = new List<Dog>();
dogs.Add(new Dog("Beagle"));
IList<Animal> animals = dogs;
animals.Add(new Cat("Domestic Short Hair"));

现在狗集合中也包含一只猫!

这使整个系统容易受到攻击,因此编译器特别防止隐式演员。

因为IEnumerable不支持Add方法或索引Setters,所以你可以毫无问题地进行转换。

And now the dogs collection contains a Cat as well!
That makes the whole system vulnerable, and so the compiler specifically prevents the implicit cast.
Because IEnumerable doesn't support an Add method or index Setters, you can convert without problems.


HI你可以使用

HI you can use
IList<string> objInt2 = new List<string>();
            IList<object> obj2 = (IList<object>)objInt2;





这个

希望它可以帮助你



this
hope it helps you


这篇关于协方差不适用于列表&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆