foreach,in(C# 参考)foreach, in (C# reference)

foreach 语句为类型实例中实现 System.Collections.IEnumerableSystem.Collections.Generic.IEnumerable<T> 接口的每个元素执行语句或语句块。The foreach statement executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface. foreach 语句不局限于这些类型,它可应用于满足以下条件的任何类型的实例:The foreach statement is not limited to those types and can be applied to an instance of any type that satisfies the following conditions:

  • 具有公共无参数 GetEnumerator 方法,其返回类型为类、结构或接口类型。has the public parameterless GetEnumerator method whose return type is either class, struct, or interface type,
  • GetEnumerator 方法的返回类型具有公共 Current 属性和公共无参数 MoveNext 方法(其返回类型为 Boolean)。the return type of the GetEnumerator method has the public Current property and the public parameterless MoveNext method whose return type is Boolean.

从 C# 7.3 开始,如果枚举器的 Current 属性返回 引用返回值ref T,其中 T 为集合元素类型),就可以使用 refref readonly 修饰符来声明迭代变量。Beginning with C# 7.3, if the enumerator's Current property returns a reference return value (ref T where T is the type of the collection element), you can declare the iteration variable with the ref or ref readonly modifier.

foreach 语句块中的任何点上,可以使用 break 语句中断循环,或者可以使用 continue 语句继续执行到循环中的下一次迭代。At any point within the foreach statement block, you can break out of the loop by using the break statement, or step to the next iteration in the loop by using the continue statement. 还可以使用 gotoreturnthrow 语句退出 foreach 循环。You also can exit a foreach loop by the goto, return, or throw statements.

如果 foreach 语句应用为 null,则会引发 NullReferenceExceptionIf the foreach statement is applied to null, a NullReferenceException is thrown. 如果 foreach 语句的源集合为空,则 foreach 循环的正文不会被执行,而是被跳过。If the source collection of the foreach statement is empty, the body of the foreach loop is not executed and skipped.

示例Examples

备注

本文中的 C# 示例运行在 Try.NET 内联代码运行程序和演练环境中。The C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行”按钮以在交互窗口中运行示例 。Select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码 。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

以下示例介绍 foreach 语句的使用,其中包含实现 IEnumerable<T> 接口的 List<T> 类型的实例:The following example shows usage of the foreach statement with an instance of the List<T> type that implements the IEnumerable<T> interface:

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");

下一个示例使用 foreach 语句,其中包含 System.Span<T> 类型的实例,该实例不实现任何接口:The next example uses the foreach statement with an instance of the System.Span<T> type, which doesn't implement any interfaces:

public class IterateSpanExample
{
    public static void Main()
    {
        Span<int> numbers = new int[] { 3, 14, 15, 92, 6 };
        foreach (int number in numbers)
        {
            Console.Write($"{number} ");
        }
        Console.WriteLine();
    }
}

下面的示例使用 ref 迭代变量来设置 stackalloc 数组中每个项的值。The following example uses a ref iteration variable to set the value of each item in a stackalloc array. ref readonly 版本循环访问该集合以打印所有值。The ref readonly version iterates the collection to print all the values. readonly 声明使用隐式局部变量声明。The readonly declaration uses an implicit local variable declaration. 隐式变量声明可与 refref readonly 声明配合使用,显式类型化变量声明也一样。Implicit variable declarations can be used with either ref or ref readonly declarations, as can explicitly typed variable declarations.

public class ForeachRefExample
{
    public static void Main()
    {
        Span<int> storage = stackalloc int[10];
        int num = 0;
        foreach (ref int item in storage)
        {
            item = num++;
        }

        foreach (ref readonly var item in storage)
        {
            Console.Write($"{item} ");
        }
        // Output:
        // 0 1 2 3 4 5 6 7 8 9
    }
}

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范中的 foreach 语句部分。For more information, see The foreach statement section of the C# language specification.

请参阅See also