gpt4 book ai didi

.net - 在数组、列表等上使用 foreach 时的排序顺序

转载 作者:行者123 更新时间:2023-12-04 16:21:03 25 4
gpt4 key购买 nike

使用 foreach 遍历数组时,是否可以保证返回元素的顺序是数组 [0]、数组 [1]、数组 [2]、...

我知道这就是现在实现 Array 类的方式,但是对框架的 future 版本有任何保证吗? List<> 也有同样的问题。

最佳答案

到目前为止,我不得不不同意所有的答案。

首先,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# Language Specification Version 3.0 ,第 240 页。

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

在具有顺序的集合中(阅读:实现 IList 或 IList(T) 的事物),这意味着元素将按照后备存储存储它们的顺序返回。

关于.net - 在数组、列表等上使用 foreach 时的排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/678162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com