C# - How to convert Listlt;Doggt; to Listlt;Animalgt;, when Dog is a subclass of Animal?(C# - 如何转换列表lt;Doggt;列出lt;Animalgt;,当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# - 如何转换列表<Dog>列出<Animal>,当Dog是Animal的子类时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# - 如何转换列表<Dog>列出<Animal>,当Dog是Animal的子类时?
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
