C# 无法在ArrayList和数组之间应用???运算符

C# 无法在ArrayList和数组之间应用???运算符,c#,arrays,arraylist,C#,Arrays,Arraylist,我有这样的代码: foreach (Type t in types ?? asm.GetTypes()) 它应该循环数组列表中的所有类型类型,如果没有提供类型,则循环程序集类型。作为System.ArrayAsSystem.Collections.ArrayList实现IEnumerable我希望该循环能够工作 然而,编译器抱怨: 运算符“??”不能应用于“System.Collections.ArrayList”和“System.type[]”类型的操作数 我想我遗漏了一些非常明显的东西,但

我有这样的代码:

foreach (Type t in types ?? asm.GetTypes())
它应该循环
数组列表中的所有类型
类型
,如果没有提供类型,则循环程序集类型。作为
System.Array
As
System.Collections.ArrayList
实现
IEnumerable
我希望该循环能够工作

然而,编译器抱怨:

运算符“??”不能应用于“System.Collections.ArrayList”和“System.type[]”类型的操作数


我想我遗漏了一些非常明显的东西,但这是什么?

2015年你不应该真正使用
ArrayList
ArrayList
不支持
IEnumerable
接口

您可以强制使用
IEnumerable
非通用接口:

foreach (Type t in (IEnumerable)types ?? asm.GetTypes())

发生错误的原因是
??
运算符没有搜索左侧和右侧之间的最小公共类型。它只是检查右类型是否可以隐式转换为左类型,或者左类型是否可以隐式转换为右类型。显然,
Type[]
无法转换为
ArrayList
ArrayList
无法转换为
Type[]
,您不能使用??两个不同结构上的运算符。您的字段“类型”应该是一个系统。键入[]才能工作。

我不知道确切的推理是什么,但我认为这是类型安全性,您可以向
数组列表添加任何内容

考虑一下

两者看起来非常相似,但现在让我们尝试向它们添加一个列表

ArrayList al = new ArrayList{1,2,3, new ArrayList()};  // succeeds
int[] il = new int[]{1,2,3, new ArrayList() };
编译错误(第12行,第31列):无法将类型“System.Collections.ArrayList”隐式转换为“int”


这让我相信,编译器认为,既然您最初希望使用arraylist,那么您并不能保证每个元素都是
类型

@HimBromBeere-ChangedWhat-is
类型
asm
GetTypes
?是否都应返回
Type
-实例?如果
s:
IEnumerable typesSeq=types,为什么不使用变量和
;如果(types==null)typesSeq=asm.GetTypes();foreach(在typesSeq中键入t).
ArrayList al = new ArrayList{1,2,3, new ArrayList()};  // succeeds
int[] il = new int[]{1,2,3, new ArrayList() };