DerivedClass>不能从列表与LT转换;列出<&的BaseClass GT; [英] Cannot convert from List<DerivedClass> to List<BaseClass>

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

问题描述

我想通过 DerivedClass 的列表,这需要的BaseClass 列表的功能,但我得到的错误:

 不能转换
System.Collections.Generic.List< ConsoleApplication1.DerivedClass>'

System.Collections.Generic.List< ConsoleApplication1.BaseClass>'

现在,我可以投我列表< D​​erivedClass> 列表< BaseClass的> ,但我不感觉很舒服这样做,除非我明白为什么编译器不允许这样。

这是我发现的解释干脆说,这违反了类型安全莫名其妙,但我没有看到它。谁能帮我?

什么是编译器允许从转换列表&LT的风险; DerivedClass> 列表< BaseClass的>


下面是我的SSCCE:

 类节目
{
    公共静态无效的主要()
    {
        BaseClass的BC =新DerivedClass(); //工作正常
        清单<&的BaseClass GT; BCL =新的List< D​​erivedClass>(); //这一行有一个错误        DoSomething的(新的List< D​​erivedClass>()); //这一行有一个错误
    }    公共无效DoSomething的(名单<&的BaseClass GT; BC)
    {
        //做一些BC
    }
}一流的BaseClass
{
}类DerivedClass:BaseClass的
{
}


解决方案

这是因为列表< T> 在变,而不是合变,所以你应该更改为的IEnumerable< T> 支持合变,它应该工作:

 的IEnumerable<&的BaseClass GT; BCL =新的List< D​​erivedClass>();
公共无效DoSomething的(IEnumerable的<&的BaseClass GT; BC)
{
    //做一些BC
}

有关通用 共同变异信息

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>'

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?

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


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
{
}

解决方案

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
}

Information about co-variant in generic

这篇关于DerivedClass&GT;不能从列表与LT转换;列出&LT;&的BaseClass GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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