简体   繁体   中英

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". The order is determined by the object's implementation of 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). 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.

It's using the IEnumerable and IEnumerator interfaces. They a providing the values one after another, so .Net does not have to care about ordering. It's processing the values just in the order as they are delivered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM