break (C# 參考)

break 陳述式會終止它所在之最靠近的封閉式迴圈或 switch 陳述式。 程式控制權轉移到終止陳述式之後的陳述式 (如果有的話)。

範例

此範例中的條件陳述式含有一個計數器,原本應該是從 1 數到 100,不過 break 陳述式在數到 4 的時候就會將迴圈終止。

class BreakTest
{
    static void Main()
    {
        for (int i = 1; i <= 100; i++)
        {
            if (i == 5)
            {
                break;
            }
            Console.WriteLine(i);
        }

        // Keep the console open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* 
 Output:
    1
    2
    3
    4  
*/

在這個範例中,break 陳述式會用於中斷內層巢狀迴圈,並且將控制項傳回外層迴圈。

class BreakInNestedLoops
{
    static void Main(string[] args)
    {

        int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        char[] letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };

        // Outer loop
        for (int x = 0; x < numbers.Length; x++)
        {
            Console.WriteLine("num = {0}", numbers[x]);

            // Inner loop
            for (int y = 0; y < letters.Length; y++)
            {
                if (y == x)
                {
                    // Return control to outer loop
                    break;
                }
                Console.Write(" {0} ", letters[y]);
            }
            Console.WriteLine();
        }

        // Keep the console open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

/*
 * Output:
    num = 0

    num = 1
     a
    num = 2
     a  b
    num = 3
     a  b  c
    num = 4
     a  b  c  d
    num = 5
     a  b  c  d  e
    num = 6
     a  b  c  d  e  f
    num = 7
     a  b  c  d  e  f  g
    num = 8
     a  b  c  d  e  f  g  h
    num = 9
     a  b  c  d  e  f  g  h  i
 */

本範例說明如何在 switch 陳述式中使用 break。

class Switch
{
    static void Main()
    {
        Console.Write("Enter your selection (1, 2, or 3): ");
        string s = Console.ReadLine();
        int n = Int32.Parse(s);

        switch (n)
        {
            case 1:
                Console.WriteLine("Current value is {0}", 1);
                break;
            case 2:
                Console.WriteLine("Current value is {0}", 2);
                break;
            case 3:
                Console.WriteLine("Current value is {0}", 3);
                break;
            default:
                Console.WriteLine("Sorry, invalid selection.");
                break;
        }

        // Keep the console open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/*
Sample Input: 1

Sample Output:
Enter your selection (1, 2, or 3): 1
Current value is 1
*/

如果您輸入 4,輸出結果就會是:

Enter your selection (1, 2, or 3): 4
Sorry, invalid selection.

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

參考

C# 關鍵字

break Statement (C++)

switch (C# 參考)

跳躍陳述式 (C# 參考)

概念

C# 程式設計手冊

其他資源

C# 參考