在数组、列表等上使用 foreach 时的排序顺序 [英] Sort order when using foreach on an array, list etc
问题描述
当使用foreach遍历一个数组时,是否有任何保证元素返回的顺序是array[0], array[1], array[2], ...
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], ...
我知道 Array 类现在是这样实现的,但是对框架的未来版本有任何保证吗?同样的问题也适用于 List<>.
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 的顺序:
First, the C# 3.0 standard guarantees the order of foreach on an array:
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# 语言规范 3.0 版,第 240 页.
-- C# Language Specification Version 3.0, page 240.
其次,在对象上,foreach (C#) 和 For Each (VB.NET) 使用对象上的 MoveNext、Reset 和 Current 成员(源).这些通常是 IEnumerator 接口的一部分.
Second, on objects, foreach (C#) and For Each (VB.NET) work by using the MoveNext, Reset, and Current members on an object (source). These are typically part of the IEnumerator interface.
在具有顺序的集合中(阅读:实现 IList 或 IList(T) 的东西),这意味着元素将按照后备存储存储它们的顺序返回.
In collections that have an order (read: things that implement IList or IList(T)), this means that the elements will be returned in the order that the backing store stores them.
这篇关于在数组、列表等上使用 foreach 时的排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!