C# 中的 foreach 循环是否保证求值顺序? [英] Does the foreach loop in C# guarantee an order of evaluation?

查看:26
本文介绍了C# 中的 foreach 循环是否保证求值顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从逻辑上讲,人们会认为 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),它通过交替的 MoveNextCurrent 调用.

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 结尾.对于多维数组,元素是遍历使得索引最右边的维度增加首先,然后是下一个左维度,等等到左边."

"The order in which foreach traverses the elements of an array, is as follows: For single-dimensional arrays elements are traversed in increasing index order, starting with index 0 and ending with index Length – 1. For multi-dimensional arrays, elements are traversed such that the indices of the rightmost dimension are increased first, then the next left dimension, and so on to the left."

这篇关于C# 中的 foreach 循环是否保证求值顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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