Convert Listlt;DerivedClassgt; to Listlt;BaseClassgt;(转换列表lt;DerivedClassgt;列出lt;BaseClassgt;)
问题描述
虽然我们可以从基类/接口继承,但为什么我们不能声明一个 List<>
使用相同的类/接口?
While we can inherit from base class/interface, why can't we declare a List<>
using same class/interface?
interface A
{ }
class B : A
{ }
class C : B
{ }
class Test
{
static void Main(string[] args)
{
A a = new C(); // OK
List<A> listOfA = new List<C>(); // compiler Error
}
}
有办法吗?
推荐答案
完成这项工作的方法是遍历列表并转换元素.这可以使用 ConvertAll 来完成:
The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
你也可以使用 Linq:
You could also use Linq:
List<A> listOfA = new List<C>().Cast<A>().ToList();
这篇关于转换列表<DerivedClass>列出<BaseClass>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:转换列表<DerivedClass>列出<BaseClass>


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01