从小孩到父母的列表分配 [英] List assignment from child to parent
问题描述
我试图这样做:
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());
$ b $ class class Parent {}
class Child:Parent {}
类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
为什么会这样?
父母[] test = new Child [10];
列表< Parent> result = test.ToList();
感谢:)
- $
现在我知道为什么了:List被编译为 List`1
并且List < List`2
。他们没有任何关系。
List< Parent>
和 List< Child>
不是 co-variant 。 即使您传入的通用参数, Child
,继承父
,则关系不会进入关闭的List类型。因此,由此产生的两种列表类型不可互换。
<。net>引入了协方差/反方差。尽管如此,你的代码仍然不能用于.NET 4.0,因为 List
类或者 IList
接口都不会被改变是共同的变体。
I am trying to do this:
List<Parent> test = new List<Child>();
The complete code of my class is this:
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 { }
Can someebody please explian me why this gives me this error:
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
And why does this work?
Parent[] test = new Child[10];
List<Parent> result = test.ToList();
Thanks :)
-- Right:
Now I know why: List is compiled to List`1
and List to List`2
. And they have no relationship.
Update: because the two types, List<Parent>
and List<Child>
is not co-variant.
Even though the generic parameter you pass in, Child
, inherits Parent
, the relationship is not carried into the closed List types. Thus, the resulting two List types are not interchangeable.
.Net 4.0 introduces co-variance/contra-variance. Your code will still not work with .Net 4.0 though, since neither the List
class or the IList
interface will be changed to be co-variant.
这篇关于从小孩到父母的列表分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!