2009-12-08 60 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

事实上,我们经常会看到这种模式用于解决缺乏界面协方差的问题。幸运的是,一旦我们在语言和基类库中有真正的接口协变,它就会开始消失。 –