的收藏我知道Passing a generic collection of objects to a method that requires a collection of the base type集合爲基本類型的C#2.0
我怎麼做.NET 2.0中,我沒有.Cast ???
它必須是參考相等的,即列表的副本不會。
再次重申 - 我不能返回新列表 - 它必須是同一列表
的收藏我知道Passing a generic collection of objects to a method that requires a collection of the base type集合爲基本類型的C#2.0
我怎麼做.NET 2.0中,我沒有.Cast ???
它必須是參考相等的,即列表的副本不會。
再次重申 - 我不能返回新列表 - 它必須是同一列表
你不知道。
在C#2和3中,不可能有引用相等並改變元素類型。在C#4中,可以使引用相等,並改變元素類型;這種轉換稱爲「協變」轉換。協變轉換將僅在IEnumerable<T>
,而非上IList<T>
或List<T>
上合法。只有當源和目標T類型是引用類型時,協變轉換纔是合法的。總之:
List<Mammal> myMammals = whatever;
List<Animal> x0 = myMammals; // never legal
IEnumerable<Mammal> x1 = myMammals; // legal in C# 2, 3, 4
IEnumerable<Animal> x2 = myMammals; // legal in C# 4, not in C# 2 or 3
IEnumerable<Giraffe> x3 = myMammals; // never legal
IList<Mammal> x4 = myMammals; // legal in C# 2, 3, 4
IList<Animal> x5 = myMammals; // never legal
IList<Giraffe> x6 = myMammals; // never legal
List<int> myInts = whatever;
IEnumerable<int> x7 = myInts; // legal
IEnumerable<object> x8 = myInts; // never legal; int is not a reference type
埃裏克是對的。他應該是被接受的答案。我會再添加一條建議。如果它是你的集合(就像你可以修改集合類一樣),即使你的集合是從Collection(Of Whatever)派生的,你也可以實現IEnumerable(Of WhateverBase)。例如,你可以實現IList(OfWhateverBase),ICollection(OfWhateverBase)等等 - 並且在你的Add方法中得到一個不兼容的類型時拋出運行時異常。
class GiraffeCollection : Collection<Giraffe>, IEnumerable<Animal> {
IEnumerator<Animal> IEnumerable<Animal>.GetEnumerator() {
foreach (Giraffe item in this) {
yield return item;
}
}
}
事實上,我們經常會看到這種模式用於解決缺乏界面協方差的問題。幸運的是,一旦我們在語言和基類庫中有真正的接口協變,它就會開始消失。 –
鑄運營商無論如何不能滿足您的要求。它不保留參考身份。 –