无法从 List 转换列出<BaseClass>
我正在尝试将 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
{
}
这是因为 List
是 in-variant
,而不是 co-variant
,所以你应该改成支持co-variant
的IEnumerable
,它应该可以工作:
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
}
有关泛型中的协变体