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


How does foreach loop work in c# i-e MSIL?

可能的重复项:
foreach 循环在 C# 中如何工作?

就像经典的迭代语句一样,如 for、while 或 do-whileis foreach loop is a new loop statment in c#?in other languages such as php

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

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>

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

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])的 for 循环不同,foreach 直接处理值。

更多在这里

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

对于数组,它经过优化以使用索引器。