c# - 集合作为基类型的集合 C# 2.0

标签 c# collections

我知道 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/

相关文章:

c# - 委托(delegate)中变量的范围

c# - CLR 级别的转换实际上是如何工作的?

c# - Wpf/WinRT点画心

java - java中读取列表时如何保留10个最大整数?

Java 集合门面

python - 禁止在 collections.defaultdict 中添加键

C# ASP 项目使用 MySql 5.5 - 参数查询语法

python - 运算符 += 与 collections.Counter 的行为不一致

java - 哪个集合是从包含 android 中键值的列表中获取值的最佳方式

c# - MSBuild构建的程序集无法注册,RegAsm(错误RA000);与 Visual Studio 2010 完全相同的 .csProj 创建有效的程序集?