簡體   English   中英

將 Derived Class Collection 分配給 Base Class Collection 編譯錯誤

[英]Assign Derived Class Collection to Base Class Collection compilation error

我有兩節課

class Base
{

}
class Derived : Base
{

}

Base base = new Derived(); 沒有編譯錯誤

如果我這樣做ICollection<Base> collBase = new List<Derived>(); 它給出了編譯錯誤。 有沒有其他方法可以解決這個問題?

如果您使用的是 .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!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM