我正在尝试这样做:
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 { }
有人可以解释一下为什么这会给我这个错误吗:
错误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();
谢谢 :)
--
正确的:
现在我知道为什么了:List 被编译为List`1
并列出至List`2
。而且他们没有任何关系。
Update:因为这两种类型,List<Parent>
and List<Child>
is not 协变体 http://msdn.microsoft.com/en-us/library/dd799517(VS.100).aspx.
即使您传入的通用参数,Child
,继承Parent
,该关系不会被带入封闭列表类型中。因此,生成的两个 List 类型不可互换。
.Net 4.0 引入了协方差/逆变。不过,您的代码仍然无法在 .Net 4.0 上运行,因为List
类或IList
接口将更改为协变。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)