在.NET中,阵列仅延IEnumerable的,所以才会有装箱和拆箱时,foreach循环遍历一个值类型的数组?会有、遍历、数组、阵列

2023-09-04 11:53:44 作者:ヤ坏脾滊╮

阵列只延长了IEnumerable的非通用版本,所以才会有装箱和拆箱时,foreach循环遍历一个值类型的数组?

Array only extends the non-generic version of IEnumerable, so will there be boxing and unboxing when a foreach loop goes through a value type array?

我猜测不是,因为那将是瘸腿的。 如果我的猜测是正确的,那么怎样的foreach经过值类型数组?这岂不是使用Array.GetEnumerator方法?如果不是,为什么阵列扩展了IEnumerable

I am guessing not, because that would be lame. If my guess is right, then how does foreach go through a value type array? Does it not use the Array.GetEnumerator method? And if not, why does Array extends IEnumerable?

感谢

推荐答案

阵列有很多在运行时特别的外壳。尤其是,它是伪通用的。也就是说,如果你指定一个像具体的数组类型T [] 实施如泛型集合接口的IEnumerable< T>

Array has a lot of special casing in the runtime. In particular it is pseudo-generic. i.e. if you specify a concrete array type like T[] implement the generic collection interfaces like IEnumerable<T>.

如果我没有记错它甚至有支持的非拳击迭代与的foreach 泛型之前的GetEnumerator 返回具体类型一个强类型当前。这工作,因为的foreach 不需要的IEnumerator / 的IEnumerable 接口,但可与正确命名的成员了。

If I recall correctly it even supported non boxing iteration with foreach before generics by having GetEnumerator return a concrete type with a strongly typed Current. This works since foreach does not require the IEnumerator/IEnumerable interfaces, but works with correctly named members too.

所以,你可以遍历与的foreach 阵列无拳。

So you can iterate over arrays with foreach without boxing.