foreach 语句对实现 System.Collections.IEnumerable 或 System.Collections.Generic.IEnumerable<T> 接口的数组或对象集合中的每个元素重复一组嵌入式语句。  foreach 语句用于循环访问集合,以获取您需要的信息,但不能用于在源集合中添加或移除项,否则可能产生不可预知的副作用。  如果需要在源集合中添加或移除项,请使用 for 循环。

嵌入语句为数组或集合中的每个元素继续执行。  当为集合中的所有元素完成迭代后,控制传递给 foreach 块之后的下一个语句。

可以在 foreach 块的任何点使用 break 关键字跳出循环,或使用 continue 关键字进入循环的下一轮迭代。

foreach 循环还可以通过 goto、return 或 throw 语句退出。


示例

以下代码显示了三个示例:

  • 显示整数数组内容的典型的 foreach 循环

  • 执行相同操作的 for 循环

  • 维护数组中的元素数计数的 foreach 循环

class ForEachTest
{    static void Main(string[] args){        int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };        foreach (int element in fibarray){System.Console.WriteLine(element);}System.Console.WriteLine();       // Compare the previous loop to a similar for loop.for (int i = 0; i < fibarray.Length; i++){System.Console.WriteLine(fibarray[i]);}System.Console.WriteLine();        // You can maintain a count of the elements in the collection.int count = 0;       foreach (int element in fibarray){count += 1;System.Console.WriteLine("Element #{0}: {1}", count, element);}System.Console.WriteLine("Number of elements in the array: {0}", count);}    // Output:// 0// 1// 1// 2// 3// 5// 8// 13// 0// 1// 1// 2// 3// 5// 8// 13// Element #1: 0// Element #2: 1// Element #3: 1// Element #4: 2// Element #5: 3// Element #6: 5// Element #7: 8// Element #8: 13// Number of elements in the array: 8}


备注:转载自https://msdn.microsoft.com/zh-cn/library/ttw7t8t6.aspx

************************************************************************

C# 还提供 foreach 语句。  该语句提供一种简单、明了的方法来循环访问数组或任何可枚举集合的元素。  foreach 语句按数组或集合类型的枚举器返回的顺序处理元素,该顺序通常是从第 0 个元素到最后一个元素。  例如,以下代码创建一个名为 numbers 的数组,并使用 foreach 语句循环访问该数组:

  int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };        foreach (int i in numbers){System.Console.Write("{0} ", i);}       // Output: 4 5 6 1 2 3 -2 -1 0

借助多维数组,你可以使用相同的方法来循环访问元素,例如:

  int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };        // Or use the short form:        // int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };foreach (int i in numbers2D){System.Console.Write("{0} ", i);}        // Output: 9 99 3 33 5 55

但对于多维数组,使用嵌套的 for 循环可以更好地控制数组元素。


备注转载自:https://msdn.microsoft.com/zh-cn/library/2h3zzhdw.aspx