从逻辑上讲,人们会认为 C# 中的 foreach 循环的计算顺序与递增 for 循环的计算顺序相同。从实验上讲,确实如此。但是,MSDN 站点上似乎没有此类确认。
难道只是因为答案如此明显以至于他们没有考虑在网站上包含该信息吗?还是有可能会出现异常行为?
最佳答案
对于数组(注意 System.Array
实现了 IEnumerable
),它将按顺序访问元素。对于其他类型( IEnumerable
或具有 GetEnumerator
),它通过交替 MoveNext
以提供的顺序访问元素和 Current
电话。
标准规定(ECMA-334 §13.9.5):
"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# - C# 中的 foreach 循环是否保证评估顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3097769/