【发布时间】:2011-06-08 12:49:43
【问题描述】:
我有两节课
class Base
{
}
class Derived : Base
{
}
Base base = new Derived();没有编译错误
如果我这样做 ICollection<Base> collBase = new List<Derived>(); 它会给出编译错误。有没有其他方法可以解决这个问题?
【问题讨论】:
-
some reading 关于协方差和反方差会有所帮助。
-
您正在使用哪个框架?如果你正在使用 stackoverflow.com/questions/833447/…
-
如果有人做了
collBase.Add(new Derived2()),您希望发生什么,其中Derived2是另一个派生自Base的类?如果您只想从collBase中读取,您可以按照@asawyer 的建议进行操作。如果没有,您需要再考虑一下。 -
@AakashM:只要他使用.net 4.0 ...如果他在较低版本上运行,@asawyer 的答案将不起作用!
-
没错,我会编辑反映。
标签: c# generics inheritance