2011-06-08 59 views
1

我有兩個類分配派生類集合基類集合編譯錯誤

class Base 
{ 

} 
class Derived : Base 
{ 

} 

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

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

+0

[一些閱讀](http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx)約協方差和反方差會有所幫助。 – 2011-06-08 12:55:23

+0

你正在使用哪種框架?如果你正在使用<4,你可能看看http://stackoverflow.com/questions/833447/why-is-this-cast-not-possible – 2011-06-08 12:55:31

+0

如果有人然後做'collBase',你會發生什麼? .Add(new Derived2())',其中'Derived2'是另一個派生自'Base'的類?如果你只想從'collBase'中讀*,你可以做@asawyer建議的。如果沒有,你需要再想一些。 – AakashM 2011-06-08 12:56:17

回答

4

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

說的對! @asawyer – 2011-06-08 12:53:52

+0

來吧...'System.Collection.Generic.List ' implements'System.Collection.ICollection ' - 那不是問題! ...我正在考慮downvote - 你應該詳細說明協變和逆變的含義 - 不僅僅是扔一些鏈接! – 2011-06-08 12:57:31

+0

@Andreas ICollection不是協變安全的,IEnumerable是因爲你不能添加到集合中。看看Eric Lipperts撰寫的一些關於這個問題的文章,他解釋得更好,然後我可以做得更好。 – asawyer 2011-06-08 13:02:17