foreach循环如何在C#中工作?

use*_*616 85 c# foreach

哪些类可以使用foreach循环?

Mar*_*ell 160

实际上,严格来说,您需要使用的foreach只是一个使用方法和属性GetEnumerator()返回内容的公共方法.但是,最常见的含义是"实现/ ,返回/的东西" .bool MoveNext()? Current {get;}IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>

通过暗示,这包括任何实现ICollection/ ICollection<T>,如像什么Collection<T>,List<T>,阵列(T[])等.因此,任何标准的"数据集"将通常支持foreach.

为了证明第一点,以下工作正常:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它是如何工作的?

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

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

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

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

  • +1深入了解.对于一个可能是"初学者"问题的问题,我通常不会那么深入,因为对于新程序员来说这似乎是无法抗拒的. (3认同)
  • 不要忘记:当使用带有foreach的数组时,编译器会创建一个简单的`for-loop`(使用IL时可以看到这个). (3认同)

Geo*_*ker 7

来自MSDN:

foreach语句为数组或对象集合每个元素重复一组嵌入式语句.该foreach语句用于迭代集合以获取所需信息,但不应用于更改集合的内容以避免不可预测的副作用.(强调我的)

所以,如果你有一个数组,你可以使用foreach语句迭代数组,如下所示:

 int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
    foreach (int i in fibarray)
    {
        System.Console.WriteLine(i);
    }
Run Code Online (Sandbox Code Playgroud)

您也可以使用它来遍历List<T>集合,如下所示:

List<string> list = new List<string>();

foreach (string item in list)
{
    Console.WriteLine(item);
}
Run Code Online (Sandbox Code Playgroud)

  • 奇怪的是,根据MSDN(http://msdn.microsoft.com/en-us/library/9yb8xew9(VS.80).aspx),对象类型不需要实现IEnumerable.任何以正确方式定义GetEnumerator,MoveNext,Reset和Current的类型都可以.很奇怪,是吗? (4认同)