English 中文(简体)
使用foreach在数组,列表等上进行排序的顺序
原标题:
  • 时间:2009-03-24 16:26:04
  •  标签:

When iterating through an array using foreach, are there any guaranties that the order in which the elements are returned is the order array[0], array[1], array[2], ...

I know this is how the Array class is implemented now but are there any guaranties for future versions of the framework? The same questions goes for List<>.

最佳回答

I d have to disagree with all the answers so far.

首先,C# 3.0标准保证了对数组的foreach顺序。

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#语言规范3.0》第240页。

其次,对于对象,foreach(C#)和ForEach(VB.NET)是通过在对象上使用MoveNext,Reset和Current成员来工作的(源自)。这些通常是IEnumerator接口的一部分。

在具有顺序的集合中(即:实现了IList或IList(T)的东西),这意味着元素将按照备份存储自己的顺序返回。

问题回答

There are no guarantees. Most list/array implementations will return values in order, but there are definitely exceptions, particularly in some of the less common collection classes. (For example, in C5, many collections return values in very different orders than they were added when enumerated.)

设计上没有保证。foreach 用于无序枚举,并暗示运行时甚至可能同时处理多个元素。您不应该依赖于任何枚举顺序。





相关问题
热门标签