foreach,in(C# 参考)

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

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

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

foreach 循环还可以通过 gotoreturnthrow 语句退出。

有关 foreach 关键字和代码示例的更多信息,请参见下面的主题:

对数组使用 foreach(C# 编程指南)

如何:使用 foreach 访问集合类(C# 编程指南)

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

  • 显示整数数组内容的典型的 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
}

C# 语言规范

有关详细信息,请参阅 C# 语言规范。该语言规范是 C# 语法和用法的权威资料。

请参阅

C# 参考

C# 编程指南

C# 关键字

迭代语句(C# 参考)

for(C# 参考)