列出从子到父的分配

Sna*_*ake 4 .net c# generics list

我想这样做:

List<Parent> test = new List<Child>();
Run Code Online (Sandbox Code Playgroud)

我班的完整代码是这样的:

class Program
{
    public static void Main(string[] args)
    {
        List<Parent> test = new List<Child>();

        test.Add(new Child());

        test.Add(new AnotherChild());
    }
}

class Parent { }

class Child : Parent { }

class AnotherChild : Parent { }
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我为什么这给了我这个错误:

错误2无法将类型'System.Collections.Generic.List'转换为'System.Collections.Generic.List'd:\ personal\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 20 24 ConsoleApplication3

为什么这有效?

Parent[] test = new Child[10];
List<Parent> result = test.ToList();
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

- 对:

现在我知道原因了:List被编译为List`1和List to List`2.他们没有任何关系.

Pet*_*old 8

更新:由于这两种类型,List<Parent>List<Child>不是共同的变体.

即使您传入的泛型参数Child,继承Parent,该关系也不会被带入关闭的List类型中.因此,生成的两个List类型不可互换.

.Net 4.0引入了协方差/反方差.但是,您的代码仍无法使用.Net 4.0,因为List类或IList接口都不会更改为共变体.