在.NET中,阵列仅延IEnumerable的,所以才会有装箱和拆箱时,foreach循环遍历一个值类型的数组? [英] In .NET, Array only extends IEnumerable, so will there be boxing and unboxing when a foreach loop goes through a value type array?

查看:224
本文介绍了在.NET中,阵列仅延IEnumerable的,所以才会有装箱和拆箱时,foreach循环遍历一个值类型的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阵列只延长了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.

这篇关于在.NET中,阵列仅延IEnumerable的,所以才会有装箱和拆箱时,foreach循环遍历一个值类型的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆