C# - 如何转换列表<Dog>列出<Animal>,当Dog是Animal的子类时? [英] C# - How to convert List<Dog> to List<Animal>, when Dog is a subclass of Animal?

查看:19
本文介绍了C# - 如何转换列表<Dog>列出<Animal>,当Dog是Animal的子类时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类Animal,以及它的子类Dog.我有一个 List<Animal>,我想将一些 List<Dog> 的内容添加到 List<Animal>.除了将 List<Dog> 转换为 List<Animal>,然后使用 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,那么您将不得不迭代 List<Dog> 并强制转换每个项目,因为那时才添加协方差.您可以通过 .Cast<T> 扩展方法完成此操作:

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# - 如何转换列表&lt;Dog&gt;列出&lt;Animal&gt;,当Dog是Animal的子类时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆