在C#中,是否有可能投一个List&LT;儿童&GT;列出&LT;家长和GT ;? [英] In C#, is it possible to cast a List<Child> to List<Parent>?
问题描述
我想要做这样的事情:
List<Child> childList = new List<Child>();
...
List<Parent> parentList = childList;
不过,由于parentList是一个孩子的祖先列表,而不是直接的祖先,我无法做到这一点。是否有解决办法(逐个添加每个元素等)?
However, because parentList is a List of Child's ancestor, rather than a direct ancestor, I am unable to do this. Is there workaround (other than adding each element individually)?
推荐答案
铸造直接是不允许的,因为没有办法让它类型安全。如果你有长颈鹿的列表,将其转换为动物的列表,你可以再放入老虎变成长颈鹿的名单!编译器也不能阻止你,因为当然虎可能会进入动物名单。唯一的地方,编译器可以阻止你是在不安全的转换。
Casting directly is not allowed because there's no way to make it typesafe. If you have a list of giraffes, and you cast it to a list of animals, you could then put a tiger into a list of giraffes! The compiler wouldn't stop you, because of course a tiger may go into a list of animals. The only place the compiler can stop you is at the unsafe conversion.
在C#4我们将支持协方差和的那些参数引用类型安全的接口和委托类型逆变。在这里看到的细节:
In C# 4 we'll be supporting covariance and contravariance of SAFE interfaces and delegate types that are parameterized with reference types. See here for details:
<一个href=\"http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx\">http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx
这篇关于在C#中,是否有可能投一个List&LT;儿童&GT;列出&LT;家长和GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!