我正在尝试这样做:
List<Parent> test = new List<Child>();
我的类的完整代码是这样的:
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 { }
有人能解释一下为什么会出现这个错误吗:
Error 2 Cannot convert type 'System.Collections.Generic.List' to '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();
谢谢:)
-- 右:
现在我知道原因了:List 被编译为 List`1
,List 被编译为 List`2
。他们没有任何关系。
最佳答案
更新:因为两种类型,List<Parent>
和 List<Child>
不是 co-variant .
即使你传入的通用参数,Child
, 继承 Parent
, 关系不带入封闭列表类型。因此,生成的两个 List 类型不可互换。
.Net 4.0 引入了协方差/反方差。但是,您的代码仍然无法与 .Net 4.0 一起使用,因为 List
都不是类或 IList
接口(interface)将更改为协变。
关于c# - 列出从 child 到 parent 的分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2396747/