DerivedClass&GT;不能从列表与LT转换;列出&LT;&的BaseClass GT; [英] Cannot convert from List<DerivedClass> to List<BaseClass>
问题描述
我想通过 DerivedClass
的列表,这需要的BaseClass
列表的功能,但我得到的错误:
不能转换
System.Collections.Generic.List&LT; ConsoleApplication1.DerivedClass&GT;'
至
System.Collections.Generic.List&LT; ConsoleApplication1.BaseClass&GT;'
现在,我可以投我列表&LT; DerivedClass&GT;
到列表&LT; BaseClass的&GT;
,但我不感觉很舒服这样做,除非我明白为什么编译器不允许这样。
这是我发现的解释干脆说,这违反了类型安全莫名其妙,但我没有看到它。谁能帮我?
什么是编译器允许从转换列表&LT的风险; DerivedClass&GT;
到列表&LT; BaseClass的&GT;
下面是我的SSCCE:
类节目
{
公共静态无效的主要()
{
BaseClass的BC =新DerivedClass(); //工作正常
清单&LT;&的BaseClass GT; BCL =新的List&LT; DerivedClass&GT;(); //这一行有一个错误 DoSomething的(新的List&LT; DerivedClass&GT;()); //这一行有一个错误
} 公共无效DoSomething的(名单&LT;&的BaseClass GT; BC)
{
//做一些BC
}
}一流的BaseClass
{
}类DerivedClass:BaseClass的
{
}
这是因为列表&LT; T&GT;
是在变
,而不是合变
,所以你应该更改为的IEnumerable&LT; T&GT;
支持合变
,它应该工作:
的IEnumerable&LT;&的BaseClass GT; BCL =新的List&LT; DerivedClass&GT;();
公共无效DoSomething的(IEnumerable的&LT;&的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屋!