我是 C# 新手。 我有一个父类声明:
class PmdTable
{
}
我有一个 child 类
class PmdSdStageCfg : PmdTable
{
现在如果我喜欢它就会提示:
List<OracleObject.PmdTable> instanceList = new List<PmdSdStageCfg>();
我收到这个错误
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collection.Generics.List'.
因为PmdTable是父类。为什么这不起作用?
请您参考如下方法:
这不起作用,因为 List<T>不是协变的。
有关详细信息,请参阅 Covariance and Contravariance in Generics .
如果允许这样做,您将能够执行完全无效的操作:
class OtherPmd : PmdTable {}
// NOTE: Non-working code below
// This will break, since it's actually a List<PmdSdStateCfg>
// But it should be allowed, since instanceList is declared List<OracleObject.PmdTable>
instanceList.Add(new OtherPmd());
