c# - 在 C# 中,是否可以将 List<Child> 转换为 List<Parent>?

标签 c# inheritance casting

我想做这样的事情:

List<Child> childList = new List<Child>();
...
List<Parent> parentList = childList;

但是,因为 parentList 是 Child 祖先的 List,而不是直接祖先,所以我无法执行此操作。是否有解决方法(除了单独添加每个元素)?

最佳答案

使用 LINQ:

List<Parent> parentList = childList.Cast<Parent>().ToList();

Documentation for Cast<>()

关于c# - 在 C# 中,是否可以将 List<Child> 转换为 List<Parent>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1777800/

相关文章:

c# - 如何将 Kendo 文本框控件绑定(bind)到它的数据?

C++ 兄弟模板类作为模板模板参数

java - 在Java中如何正确地转换接口(interface)?

c# - 无法将 'System.Int32' 类型的对象转换为 'System.Int64' 类型

c# - 如何使用 XAML 将数据绑定(bind)到祖先元素中的属性?

c# - 如何使用 c# 和 Google API 在 Google 日历中创建事件?

c# - 在 C# 中居中显示窗体

java - 当接口(interface) A 在其方法签名中定义接口(interface) B 时

c++ - 协变虚函数返回类型问题

java - 如何在 Java 中将 float 转换为整数