在C#中,可以将List< Child>到列表<父>? [英] In C#, is it possible to cast a List<Child> to List<Parent>?
问题描述
我想做这样的事情:
List<Child> childList = new List<Child>();
...
List<Parent> parentList = childList;
但是,因为parentList是Child的祖先 List ,而不是直接祖先,我不能这样做。是否有解决方法(单独添加每个元素除外)?
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中,我们将支持SAFE接口的协方差和逆变,以及参数化的委托类型参考类型。详情请参阅:
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:
http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx
这篇关于在C#中,可以将List< Child>到列表<父>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!