C# - 如何名单<转换;狗>列出<当狗是动物的一个子类动物>中? [英] C# - How to convert List<Dog> to List<Animal>, when Dog is a subclass of Animal?
问题描述
我有一个类动物
和它的子类狗
。
我有一个列表<动物>
,我想补充一些内容列表<狗>
在列表与LT;动物>
。
是否有更好的方式来做到这一点,不仅仅是投了列表<狗>
到列表<动物>
,然后用的AddRange
?
I have a class Animal
, and its subclass Dog
.
I have a List<Animal>
and I want to add the contents of some List<Dog>
to the List<Animal>
.
Is there a better way to do so, than just cast the List<Dog>
to a List<Animal>
, and then use AddRange
?
推荐答案
您别ŧ如果你使用C#4所需要的转换:
You don't need the cast if you're using C#4:
List<Animal> animals = new List<Animal>();
List<Dog> dogs = new List<Dog>();
animals.AddRange(dogs);
这是允许的,因为的AddRange()
接受一个的IEnumerable< T>
,这是的协变。
That's allowed, because AddRange()
accepts an IEnumerable<T>
, which is covariant.
如果你没有C#4,但是,那么你就必须遍历名单,LT ;狗>
和投每个项目,因为只增加协方差即可。
If you don't have C#4, though, then you would have to iterate the List<Dog>
and cast each item, since covariance was only added then. You can accomplish this via the .Cast<T>
extension method:
animals.AddRange(dogs.Cast<Animal>());
如果您甚至不必C#3.5,那么你就必须做手工铸造
If you don't even have C#3.5, then you'll have to do the casting manually.
这篇关于C# - 如何名单<转换;狗>列出<当狗是动物的一个子类动物>中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!