我知道 Passing a generic collection of objects to a method that requires a collection of the base type
我如何在没有 .Cast 的 .Net 2.0 中执行此操作???
它必须是引用相等性,即列表的副本不会。
要重新迭代 - 我不能返回一个新列表 - 它必须是同一个列表
最佳答案
你不知道。
在 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
关于c# - 集合作为基类型的集合 C# 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1866704/