foreach循环如何在c#i-e MSIL中工作?

时间:2012-07-03 18:03:43

标签: c# php .net loops foreach

  

可能重复:
  How do foreach loops work in C#?

就像经典的迭代声明,例如 for,while or do-while is foreach loop is a new loop statment in c#?in other languages such as php

在幕后,它将我们的代码转换为for,while或do-while循环。

3 个答案:

答案 0 :(得分:8)

foreach结构相当于:

IEnumerator enumerator = myCollection.GetEnumerator();
try
{
   while (enumerator.MoveNext())
   {
       object current = enumerator.Current;
       Console.WriteLine(current);
   }
}
finally
{
   IDisposable e = enumerator as IDisposable;
   if (e != null)
   {
       e.Dispose();
   }
}

请注意,此版本是非通用版本。编译器可以处理IEnumerator<T>

答案 1 :(得分:4)

它不是一个新的循环。它从一开始就存在。

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.

class ForEachTest
{
    static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };

        foreach (int i in fibarray)
            System.Console.WriteLine(i);
    }

}

输出

0
1
2
3
5
8
13

与用于索引和访问值的循环(如array [index])不同,foreach直接用于值。

更多here

答案 2 :(得分:0)

它是一个while循环infact并且它使用容器的GetEnumerator()方法,有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/aa664754(v=vs.71).aspx

对于数组,它被优化为使用索引器。