foreach 和in的用法

来源:互联网 发布:java贪吃蛇源代码下载 编辑:程序博客网 时间:2024/05/21 21:48

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/foreach-in


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

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

在 foreach 块中的任何点上,可以使用中断关键字中断该循环,或者可以使用继续关键字单步执行到循环中的下一次迭代。

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

有关 foreach 关键字和代码示例的详细信息,请参阅下列主题:

对数组使用 foreach

如何:使用 foreach 访问集合类

示例

下面的代码演示了三个示例:

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

  • 执行相同操作的 for 循环

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

C#
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}