的收藏我知道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;
}
}
}
事实上,我们经常会看到这种模式用于解决缺乏界面协方差的问题。幸运的是,一旦我们在语言和基类库中有真正的接口协变,它就会开始消失。 –
铸运营商无论如何不能满足您的要求。它不保留参考身份。 –