【发布时间】:2012-12-10 14:29:19
【问题描述】:
可能重复:
C# variance problem: Assigning List<Derived> as List<Base>
我遇到了列表继承问题。看起来具有更多指定成员的通用列表无法转换为具有其基本成员的列表。 看看这个:
class A
{
public int aValue {get; set;}
}
class B : A
{
public int anotherValue {get; set;}
}
您现在可能认为List<B> 也是List<A>,但事实并非如此。
List<A> myList = new List<B>() 是不可能的。甚至List<A> myList = (List<A>)new List<B>() 在面向对象编程工作 3 年后,我是否在这里遗漏了一些基本概念?
【问题讨论】:
-
泛型在 .NET 中的工作方式
-
这就是协方差在 .NET 中对于泛型的工作方式。您必须创建一个中间接口。不久前我有same question。
标签: c# list generics inheritance