无法从 List<DerivedClass> 转换列出&lt;BaseClass&gt; [英] Cannot convert from List&lt;DerivedClass&gt; to List&lt;BaseClass&gt;

查看:32
本文介绍了无法从 List<DerivedClass> 转换列出&lt;BaseClass&gt;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to pass A list of DerivedClass to a function that takes a list of BaseClass, but I get the error:

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

现在我可以将我的 List 转换为 List,但我不喜欢这样做,除非我明白编译器为什么不这样做不允许这样做.

Now I could cast my List<DerivedClass> to a List<BaseClass>, but I don't feel comfortable doing that unless I understand why the compiler doesn't allow this.

我发现的解释只是说它以某种方式违反了类型安全,但我没有看到.谁能帮帮我?

Explanations that I have found have simply said that it violates type safety somehow, but I'm not seeing it. Can anyone help me out?

编译器允许从 List 转换为 List 的风险是什么?

What is the risk of the compiler allowing conversion from List<DerivedClass> to List<BaseClass>?

这是我的 SSCCE:

Here's my 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
{
}

推荐答案

这是因为 Listin-variant,而不是 co-variant,所以你应该改成支持co-variantIEnumerable,它应该可以工作:

It is because List<T> is in-variant, not co-variant, so you should change to IEnumerable<T> which supports co-variant, it should work:

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

有关泛型中的协变体

这篇关于无法从 List<DerivedClass> 转换列出&lt;BaseClass&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆