[英]How does .net determine the order for the “foreach” loop?
当我在C#.net中使用foreach
语句时,.net如何确定以什么顺序处理集合中的元素?
When you use foreach
, the object which implements IEnumerable
or IEnumerable<T>
is "iterated". 当使用foreach
,实现IEnumerable
或IEnumerable<T>
的对象被“迭代”。 The order is determined by the object's implementation of IEnumerable
. 顺序由对象的IEnumerable
实现确定。
Any class can customize the order in which this occurs. 任何类都可以自定义发生的顺序。 With a List<T>
, for example, it's in the list's order (by index). 例如,使用List<T>
,它以列表的顺序(按索引)排列。 However, some classes such as Dictionary<T,U>
do not guarantee an order at all - only that each item will get enumerated through one time, as providing an ordering guarantee in that case would dramatically hamper performance. 但是,某些类(例如Dictionary<T,U>
根本无法保证顺序-只能逐项枚举每个项目,因为在这种情况下提供顺序保证会极大地影响性能。
It's using the IEnumerable and IEnumerator interfaces. 它使用IEnumerable和IEnumerator接口。 They a providing the values one after another, so .Net does not have to care about ordering. 它们一个接一个地提供值,因此.Net不必在乎顺序。 It's processing the values just in the order as they are delivered. 它按照交付时的顺序处理这些值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.