列出从子到父的分配

我想这样做:

List test = new List(); 

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

 class Program { public static void Main(string[] args) { List test = new List(); test.Add(new Child()); test.Add(new AnotherChild()); } } class Parent { } class Child : Parent { } class AnotherChild : Parent { } 

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

错误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 result = test.ToList(); 

谢谢 :)

– 对:

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

更新:因为ListList这两种类型不是共变体 。

即使您传入的generics参数Childinheritance了Parent ,也不会将关系带入已关闭的List类型。 因此,生成的两个List类型不可互换。

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

您不能这样做,因为List不能分配给List ,即使Child 可以分配给ParentList类型是不变的。

你有什么理由不能使用这样的东西吗?

 public static void Main(string[] args) { List test = new List(); test.Add(new Child()); test.Add(new AnotherChild()); } 

用这个

  List test = new List().Cast().ToList(); 

C#中的generics是不变的,这意味着generics类型的不同实例之间没有子类型关系。

从概念上讲, List不能是List的子类型,因为您可以将AnotherChild的实例插入List ,但不能插入List

我建议你这个artice(它有很好的协方差和逆变描述。): http ://blog.tlk.com/dot-net/2009/c-sharp-4-covariance-and-contravariance