简体   繁体   English

通用集合中的协方差

[英]Covariance in generic collections

I would like to do this 我想这样做

List<anotherclass> ls = new List<anotherclass> {new anotherclass{Name = "me"}};    
myGrid.ItemSource = ls;

at some other place 在其他地方

var d = myGrid.ItemSource as IEnumerable<Object>;    
var e = d as ICollection<dynamic>;
e.Add(new anotherclass());

I need to access the itemsource at different areas of the program. 我需要在程序的不同区域访问itemsource。 I need to add items to the List without compile time type information. 我需要将项目添加到列表,而无需编译时间类型信息。 Casting to IEnumerable works, but because I need to add items to the collection I need more than that, hence trying to cast it to a collection. 强制转换为IEnumerable的作品,但是因为我需要向集合中添加项目,所以我需要的更多,因此尝试将其强制转换为集合。

How can it be possible? 怎么可能呢?

List<T> implements IList . List<T>实现IList So as long as you're sure you're adding the right type of object, you can use the Add method of this interface: 因此,只要您确定要添加正确类型的对象,就可以使用此接口的Add方法:

var d = (IList)myGrid.ItemSource;        
d.Add(new anotherclass());

The question is not: "Why does it work?", because, in fact, it doesn't work. 问题不是:“为什么它起作用?”,因为实际上它不起作用。 It compiles but it will throw a NullReferenceException . 它可以编译,但是会抛出NullReferenceException
d as ICollection<dynamic> will return null because an List<anotherclass> isn't an ICollection<dynamic> but an ICollection<anotherclass> and ICollection<T> is not covariant. d as ICollection<dynamic>将返回null因为List<anotherclass>不是ICollection<dynamic>但是ICollection<anotherclass>ICollection<T>不是协变的。

The solution already has been provided by KooKiz . 该解决方案已经由KooKiz提供。

Try this instead: 尝试以下方法:

var d =(List<anotherclass>) myGrid.ItemSource;
d.Add(new anotherclass());

I think it is better to do a direct cast. 我认为直接铸造更好。 If you use as it will throw a nullreferenceException when trying to add. 如果使用,则尝试添加时将抛出nullreferenceException。 It is better to have the invalidCastException that better describes what went wrong. 最好具有invalidCastException,它可以更好地描述出了什么问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM