问题描述
从逻辑上讲,人们会认为 C# 中的 foreach 循环的计算顺序与递增的 for 循环相同.实验上,确实如此.但是,MSDN 站点上似乎没有这样的确认.
Logically, one would think that the foreach loop in C# would evaluate in the same order as an incrementing for loop. Experimentally, it does. However, there appears to be no such confirmation on the MSDN site.
这是否只是一个如此明显的答案,以至于他们不认为在网站上包含该信息?或者它是否有可能表现不正常?
Is it simply such an apparent answer that they did not think to include that information on the site? Or is there the possibility that it will behave erratically?
推荐答案
对于数组(注意System.Array
实现了IEnumerable
),它会按顺序访问元素.对于其他类型(IEnumerable
或具有 GetEnumerator
),它通过交替的 MoveNext
和 Current
调用.
For arrays (note that System.Array
implements IEnumerable
), it will access elements in order. For other types (IEnumerable
, or having GetEnumerator
), it accesses elements in the order provided, through alternating MoveNext
and Current
calls.
标准规定(ECMA-334 §13.9.5):
The standard states (ECMA-334 §13.9.5):
"foreach遍历的顺序数组的元素是如下: 对于一维数组元素以递增的方式遍历索引顺序,从索引 0 开始,然后以索引 Length – 1 结尾.对于多维数组,元素是遍历使得索引最右边的维度增加首先,然后是下一个左维度,等等到左边."
这篇关于C# 中的 foreach 循环是否保证求值顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!