【问题标题】:Assign Derived Class Collection to Base Class Collection compilation error将派生类集合分配给基类集合编译错误
【发布时间】: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


【解决方案1】:

如果您使用的是 .Net 版本 4:将 ICollection 更改为 IEnumerable

http://msdn.microsoft.com/en-us/library/dd799517.aspx

编辑 - 更有用的阅读

http://blogs.msdn.com/b/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx

http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/default.aspx

试图进一步澄清为什么你不能这样做:

class animal {}
class dog : animal {}
class cat : animal {}

ICollection<animal> dogs = new List<dog>(); //error (Or List<T>, same error) because...
dogs.Add(new cat()); //you just dogged a cat

IEnumerable<animal> dogs = new List<dog>(); // this is ok!

【讨论】:

  • 来吧...System.Collection.Generic.List&lt;T&gt; 实现System.Collection.ICollection&lt;T&gt; - 这不是问题! ...我正在考虑投反对票-您应该详细说明协变和逆变的含义-不仅要插入一些链接!
  • @Andreas ICollection 不是协变安全的,IEnumerable 是因为您无法添加到集合中。看看 Eric Lipperts 就该主题撰写的一些文章,他对事情的解释比我以往任何时候都好。
  • @asawyer:另一个重要的事实:.net 版本 ... :) 顺便说一句 ...感谢您的详细说明 - 现在更清楚了!
  • @asawyer IEnumerable&lt;animal&gt; dogs = new List&lt;dog&gt;(); // this is ok! 也给出了错误:(
  • @praveen:请详细说明:您使用的是哪个 .net 版本!
猜你喜欢
  • 2011-04-14
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 2013-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多