无法在 ArrayList 和 Array 之间应用 ??-operator [英] Cannot apply ??-operator between an ArrayList and an Array
问题描述
我有这样的代码:
foreach (Type t in types ?? asm.GetTypes())
哪个应该循环 ArrayList
types
或程序集类型中的所有类型,如果没有提供类型.由于 System.Array
和 System.Collections.ArrayList
都实现了 IEnumerable
,我希望该循环能够正常工作.
Which should loop all types in the ArrayList
types
or the assemblies types if no types are provided. As both System.Array
as System.Collections.ArrayList
implement IEnumerable
I´d expect that loop to work.
然而编译器抱怨:
运算符??"不能应用于类型为System.Collections.ArrayList"和System.Type[]"的操作数
Operator '??' cannot be applied to operands of type 'System.Collections.ArrayList' and 'System.Type[]'
我想我遗漏了一些非常明显的东西,但它是什么?
I suppose I am missing something very obvious, but what is it?
推荐答案
你真的不应该在 2015 年使用 ArrayList
.ArrayList
不支持 IEnumerable<>
接口.
You shouldn't really use ArrayList
in 2015. ArrayList
doesn't support the IEnumerable<>
interface.
您可以强制使用 IEnumerable
非通用接口:
You can force the using of the IEnumerable
non-generic interface:
foreach (Type t in (IEnumerable)types ?? asm.GetTypes())
您的错误发生是因为 ??
运算符没有搜索左右之间的最小公共类型.它只是检查是否可以将右类型隐式转换为左类型,或者是否可以将左类型隐式转换为右类型.显然Type[]
不能转换为ArrayList
,ArrayList
不能转换为Type[]
.
Your error happens because the ??
operator doesn't search for the minimum common type between left and right. It simply checks if right type can be implicitly converted to left type or if left type can be implicitly converted to right type. Clearly Type[]
can't be converted to ArrayList
and ArrayList
can't be converted to Type[]
.
这篇关于无法在 ArrayList 和 Array 之间应用 ??-operator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!