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 方法的傳回型別為 Booleanthe return type of the GetEnumerator method has the public Current property and the public parameterless MoveNext method whose return type is Boolean.

您可以在 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.

範例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.

下面範例針對實作 IEnumerable<T> 介面的 List<T> 型別執行個體,示範搭配 foreach 陳述式時的使用方式: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();
    }
}

從 C# 7.3 開始,如果列舉值的 Current 屬性會傳回參考傳回值 (T 是集合元素類型的 ref 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. 下列範例會使用 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# 語言規格>。For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also