foreach 循环如何在 C# 中工作? [英] How do foreach loops work in C#?

查看:24
本文介绍了foreach 循环如何在 C# 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪些类型的类可以使用 foreach 循环?

Which types of classes can use foreach loops?

推荐答案

其实,严格来说,你只需要使用 foreach 就是一个公共的 GetEnumerator() 方法返回带有 bool MoveNext() 方法和 的内容?当前 {get;} 属性.然而,最常见的含义是实现IEnumerable/IEnumerable的东西,返回一个IEnumeratorcode>/IEnumerator.

Actually, strictly speaking, all you need to use foreach is a public GetEnumerator() method that returns something with a bool MoveNext() method and a ? Current {get;} property. However, the most common meaning of this is "something that implements IEnumerable/IEnumerable<T>, returning an IEnumerator/IEnumerator<T>.

暗示,这包括任何实现 ICollection/ICollection 的东西,例如像 CollectionList、数组 (T[]) 等.因此,任何标准的数据集合"都适用.一般会支持foreach.

By implication, this includes anything that implements ICollection/ICollection<T>, such as anything like Collection<T>, List<T>, arrays (T[]), etc. So any standard "collection of data" will generally support foreach.

对于第一点的证明,以下工作正常:

For proof of the first point, the following works just fine:

using System;
class Foo {
    public int Current { get; private set; }
    private int step;
    public bool MoveNext() {
        if (step >= 5) return false;
        Current = step++;
        return true;
    }
}
class Bar {
    public Foo GetEnumerator() { return new Foo(); }
}
static class Program {
    static void Main() {
        Bar bar = new Bar();
        foreach (int item in bar) {
            Console.WriteLine(item);
        }
    }
}

它是如何工作的?

foreach(int i in obj) {...} 这样的 foreach 循环有点等同于:

A foreach loop like foreach(int i in obj) {...} kinda equates to:

var tmp = obj.GetEnumerator();
int i; // up to C# 4.0
while(tmp.MoveNext()) {
    int i; // C# 5.0
    i = tmp.Current;
    {...} // your code
}

但是,有变化.例如,如果枚举器(tmp)支持IDisposable,则也使用它(类似于using).

However, there are variations. For example, if the enumerator (tmp) supports IDisposable, it is used too (similar to using).

注意声明int i"位置的区别内部(C# 5.0)与外部(C# 4.0以上)循环.如果您在代码块内的匿名方法/lambda 中使用 i,这一点很重要.但那是另外一回事了;-p

Note the difference in the placement of the declaration "int i" inside (C# 5.0) vs. outside (up C# 4.0) the loop. It's important if you use i in an anonymous method/lambda inside your code-block. But that is another story ;-p

这篇关于foreach 循环如何在 C# 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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