每个循环的 C# 以什么顺序迭代 List<T>? [英] In what order does a C# for each loop iterate over a List<T>?
问题描述
我想知道 C# 中的 foreach 循环遍历 System.Collections.Generic.List
对象的顺序.
I was wondering about the order that a foreach loop in C# loops through a System.Collections.Generic.List<T>
object.
我发现了另一个问题相同的主题,但我觉得它不能让我满意地回答我的问题.
I found another question about the same topic, but I do not feel that it answers my question to my satisfaction.
有人说没有定义顺序.但正如其他人所说,它遍历数组的顺序是固定的(从 0 到 Length-1).8.8.4 foreach 语句
Someone states that no order is defined. But as someone else states, the order it traverses an array is fixed (from 0 to Length-1). 8.8.4 The foreach statement
也有人说这同样适用于任何具有顺序的标准类(例如 List
).我找不到任何文件来支持它.所以就我所知,它现在可能会这样工作,但也许在下一个 .NET 版本中它会有所不同(即使它可能不太可能).
It was also said that the same holds for any standard classes with an order (e.g. List<T>
). I can not find any documentation to back that up. So for all I know it might work like that now, but maybe in the next .NET version it will be different (even though it might be unlikely).
我还查看了 List(t).Enumerator
没有运气的文档.
I have also looked at the List(t).Enumerator
documentation without luck.
另一个相关问题指出,对于 Java,在文档:
Another related question states that for Java, it is specifically mentioned in the documentation:
List.iterator()
返回一个遍历这个列表中元素的迭代器以正确的顺序."
List.iterator()
returns an iterator over the elements in this list in proper sequence."
我正在 C# 文档中寻找类似的内容.
I am looking for something like that in the C# documentation.
提前致谢.
感谢大家的回答(我收到这么多回复的速度太快了).我从所有答案中了解到的是 List
确实总是按照其索引的顺序进行迭代.但我仍然希望看到清晰的文档说明这一点,类似于 List
上的 Java 文档.
Thank you for all you for all your answers (amazing how fast I got so many replies). What I understand from all the answers is that List<T>
does always iterate in the order of its indexing. But I still would like to see a clear peace of documentation stating this, similar to the Java documentation on List
.
推荐答案
On List
On Microsoft Reference Source page for List<T>
Enumerator it is explicitly stated that the iteration is done from 0 to Length-1:
internal Enumerator(List<T> list) {
this.list = list;
index = 0;
version = list._version;
current = default(T);
}
public bool MoveNext() {
List<T> localList = list;
if (version == localList._version && ((uint)index < (uint)localList._size))
{
current = localList._items[index];
index++;
return true;
}
return MoveNextRare();
}
希望它仍然与某人相关
这篇关于每个循环的 C# 以什么顺序迭代 List<T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!