我正在尝试将一个 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
{
}
List<Derived>
并不继承自List<Base>
。 - Tim SchmelterGeneric<Derived>
可以被认为是从Generic<Base>
派生而来?或者这样的功能是否会引起问题? - Sam I am says Reinstate MonicaList<Base>
。 - voithos