c# - C# 中的 foreach 循环是否保证评估顺序?

标签 c# foreach

从逻辑上讲,人们会认为 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/

相关文章:

javascript - 如何在 jQuery onload 中选中复选框

php - Laravel 使用过滤器和映射而不是 foreach

c# - 如何在不重复的文本框中制作图像

c# - 对线程池输出进行排序以流式传输数据

c# - C# 中的命名空间是否类似于 Java 中的包

XSLT:如果满足条件,如何退出 "for-each"循环

c# - 使用 C# 为 MySQL 转换 DateTime

c# - ASP.NET CORE 版本中的 HttpContext.Current.Request.Form.AllKeys

php - foreach 不填充数组

list - 访问Stata中的列表元素