共用方式為


goto (C# 參考)

更新:2007 年 11 月

goto 陳述式將程式控制直接轉移到標記陳述式。

goto 的常見用法是轉移控制至特定的 switch-case 標記或 switch 陳述式中預設的標記。

goto 陳述式對於跳出複雜的巢狀迴圈也很有用。

範例

下列範例說明在 switch 陳述式中使用 goto。

class SwitchTest
{
    static void Main()
    {
        Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
        Console.Write("Please enter your selection: ");
        string s = Console.ReadLine();
        int n = int.Parse(s);
        int cost = 0;
        switch (n)
        {
            case 1:
                cost += 25;
                break;
            case 2:
                cost += 25;
                goto case 1;
            case 3:
                cost += 50;
                goto case 1;
            default:
                Console.WriteLine("Invalid selection.");
                break;
        }
        if (cost != 0)
        {
            Console.WriteLine("Please insert {0} cents.", cost);
        }
        Console.WriteLine("Thank you for your business.");
    }
}
/*
Sample Input:  2

Sample Output:
Coffee sizes: 1=Small 2=Medium 3=Large
Please enter your selection: 2
Please insert 50 cents.
Thank you for your business.
*/

以下的範例說明使用 goto 以中斷巢狀迴圈。

public class GotoTest1
{
    static void Main()
    {
        int x = 200, y = 4;
        int count = 0;
        string[,] array = new string[x, y];

        // Initialize the array:
        for (int i = 0; i < x; i++)

            for (int j = 0; j < y; j++)
                array[i, j] = (++count).ToString();

        // Read input:
        Console.Write("Enter the number to search for: ");

        // Input a string:
        string myNumber = Console.ReadLine();

        // Search:
        for (int i = 0; i < x; i++)
        {
            for (int j = 0; j < y; j++)
            {
                if (array[i, j].Equals(myNumber))
                {
                    goto Found;
                }
            }
        }

        Console.WriteLine("The number {0} was not found.", myNumber);
        goto Finish;

    Found:
        Console.WriteLine("The number {0} is found.", myNumber);

    Finish:
        Console.WriteLine("End of search.");
    }
}
/*
Sample Input: 44

Sample Output
Enter the number to search for: 44
The number 44 is found.
End of search.
*/

C# 語言規格

如需詳細資料,請參閱 C# 語言規格中的下列章節:

  • 5.3.3.10 Break 陳述式、continue 陳述式和 goto 陳述式

  • 8.9.3 goto 陳述式

請參閱

概念

C# 程式設計手冊

參考

C# 關鍵字

The goto Statement

跳躍陳述式 (C# 參考)

其他資源

C# 參考