2009-12-08 63 views

回答

0

你想:

List<T>.ConvertAll() 

See here獲取更多信息。

+2

這不符合列表中引用相等的聲明要求。 –

8

你不知道。

在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 
1

埃裏克是對的。他應該是被接受的答案。我會再添加一條建議。如果它是你的集合(就像你可以修改集合類一樣),即使你的集合是從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; 
     } 
    } 

} 
+0

事實上,我們經常會看到這種模式用於解決缺乏界面協方差的問題。幸運的是,一旦我們在語言和基類庫中有真正的接口協變,它就會開始消失。 –