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
- 从 C# 控制相机设备 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
