从子级到父级的列表赋值

4

我想要做到这一点:

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则被编译成List`2。它们之间没有关系。

5个回答

8

更新:由于两种类型List<Parent>List<Child>不是协变的。

即使您传递的泛型参数Child继承了Parent,这种关系也没有体现在封闭的List类型中。因此,生成的两个List类型不能互换。

.Net 4.0引入了协变/反变。但是,您的代码仍然无法在.Net 4.0中工作,因为List类或IList接口都不会更改为协变。


3

你不能这样做,因为List<Child>无法赋值给List<Parent>,即使Child可以赋值给ParentList<T>类型是不变的。

有没有什么原因不能使用类似下面这样的替代方案呢?

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

    test.Add(new Child());

    test.Add(new AnotherChild());
}

这个可以运行,但我想知道原因。现在我明白了。谢谢。 - Snake

1
请使用此代码。
 List<Parent> test = new List<Child>().Cast<Parent>().ToList();

1

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

从概念上讲,List<Child>不能是List<Parent>的子类型,因为你可以将AnotherChild的实例插入到List<Parent>中,但不能插入到List<Child>中。


1
请注意,在C# 4中将有有限的泛型变异。在这种情况下不会有任何区别,但您将能够从IEnumerable<Child>转换为IEnumerable<Parent> - Jon Skeet
有趣,我不知道这一点。谢谢! - meriton

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接