List <T>继承表现奇怪

Mec*_*MK1 0 c# generics inheritance list

可能重复:
C#方差问题:将List <Derived>分配为List <Base>

我有列表继承的问题.它看起来像具有更多指定成员的通用List无法转换为具有其基本成员的列表.看这个:

class A
{
    public int aValue {get; set;}
}

class B : A
{
    public int anotherValue {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

你现在可能期望a List<B>也是一个,List<A>但事实并非如此. List<A> myList = new List<B>()不可能.甚至List<A> myList = (List<A>)new List<B>()在面向对象编程3年后,我是否遗漏了一些基本概念?

Raw*_*ing 6

对!

假设你能做到

List<A> myList = new List<B>();
Run Code Online (Sandbox Code Playgroud)

假设你有一个班级

class C : A { public int aDifferentValue { get; set; } }
Run Code Online (Sandbox Code Playgroud)

A C是一个A,所以你希望能够打电话,myList.Add(new C())因为myList它认为它是一个List<A>.

但是,一个C不是B这样的myList- 这真的List<B>- 不能持有C.


相反,假设你可以这样做

List<B> myList = new List<A>();
Run Code Online (Sandbox Code Playgroud)

你可以愉快地打电话,myList.Add(new B())因为a B是一个A.

但是假设其他东西卡C在你的列表中(就像CA).

然后myList[0]可能会返回一个C- 这不是一个B.