如何获得 foreach 循环当前迭代的索引? [英] How do you get the index of the current iteration of a foreach loop?

查看:46
本文介绍了如何获得 foreach 循环当前迭代的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中是否有一些我没有遇到过的罕见语言结构(比如我最近学到的一些,一些在 Stack Overflow 上)来获取表示 foreach 循环当前迭代的值?

Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?

例如,我目前根据情况做这样的事情:

For instance, I currently do something like this depending on the circumstances:

int i = 0;
foreach (Object o in collection)
{
    // ...
    i++;
}

推荐答案

foreach 用于迭代实现 IEnumerable.它通过调用 GetEnumerator 在集合上,这将返回一个 Enumerator.

The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

这个枚举器有一个方法和一个属性:

This Enumerator has a method and a property:

  • MoveNext()
  • 当前

Current 返回 Enumerator 当前所在的对象,MoveNextCurrent 更新为下一个对象.

Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.

索引的概念与枚举的概念无关,无法做到.

The concept of an index is foreign to the concept of enumeration, and cannot be done.

因此,大多数集合都可以使用索引器和 for 循环结构进行遍历.

Because of that, most collections are able to be traversed using an indexer and the for loop construct.

与使用局部变量跟踪索引相比,我更喜欢在这种情况下使用 for 循环.

I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.

这篇关于如何获得 foreach 循环当前迭代的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆