在 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 a 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:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/
这篇关于在 C# 中,是否可以将 List<Child>列出<父级>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!