小编典典

无法从列表转换 列出

c#

我正在尝试将A的列表传递DerivedClass给采用的列表的函数BaseClass,但出现错误:

cannot convert from 
'System.Collections.Generic.List<ConsoleApplication1.DerivedClass>' 
to 
'System.Collections.Generic.List<ConsoleApplication1.BaseClass>'

现在,我可以将其强制List<DerivedClass>转换为List<BaseClass>,但是这样做不舒服,除非我理解为什么编译器不允许这样做。

我发现的解释只是说它某种程度上违反了类型安全性,但我没有看到它。谁能帮我吗?

编译器允许从List<DerivedClass>到转换的风险是什么List<BaseClass>


这是我的SSCCE:

class Program
{
    public static void Main()
    {
        BaseClass bc = new DerivedClass(); // works fine
        List<BaseClass> bcl = new List<DerivedClass>(); // this line has an error

        doSomething(new List<DerivedClass>()); // this line has an error
    }

    public void doSomething(List<BaseClass> bc)
    {
        // do something with bc
    }
}

class BaseClass
{
}

class DerivedClass : BaseClass
{
}

阅读 194

收藏
2020-05-19

共1个答案

小编典典

这是因为List<T>is in-variant而不是co-variant,所以您应该更改为IEnumerable<T>support
co-variant,它应该起作用:

IEnumerable<BaseClass> bcl = new List<DerivedClass>();
public void doSomething(IEnumerable<BaseClass> bc)
{
    // do something with bc
}

有关泛型协变量的信息

2020-05-19