Share via


switch (C# 參考)

更新:2010 年 9 月

switch 陳述式是選取「Switch 區段」(Switch Section) 從候選項清單執行的控制陳述式。

每個 swith 區段包含一個或多個案例標籤,以及一或多個陳述式的清單。 下列範例示範有三個 Switch 區段的簡單 switch 陳述式。 每個 switch 區段有一個案例標籤,例如case 1,以及兩個陳述式的清單。

範例

int caseSwitch = 1;
switch (caseSwitch)
{
    case 1:
        Console.WriteLine("Case 1");
        break;
    case 2:
        Console.WriteLine("Case 2");
        break;
    default:
        Console.WriteLine("Default case");
        break;
}

每個案例標籤指定一個常數值。 控制權會轉移到其 case 標籤包含符合「Switch 運算式」(Switch Expression) 值 caseSwitch 之常數值的 switch 區段。 如果沒有案例標籤包含相符的值,會將控制項轉換到 default 區段,如果有的話。 如果沒有 default 區段,則不會採取任何動作,控制權會轉移到 switch 陳述式之外。 在上一個範例中,會執行第一個 swith 區段中的陳述式,因為案例標籤case 1指定值 1,且 caseSwitch 的值也是 1。

switch 陳述式可包含任意數量的 switch 區段,每一個區段可以有一個或多個 case 標籤。 但是,沒有兩個案例標籤可以包含相同的常數值。

執行陳述式清單中的選定區段 (以第一個陳述式開頭,繼續進行陳述式清單,通常直到達到跳躍陳述式為止,例如break,goto case,return,或throw)。 在這種情況下,會將控制項傳遞到 switch 陳述式以外或傳遞到另一個案例標籤。

與 C++ 不同,C# 不允許執行從一個 switch 區段繼續到下一個區段。 下列程式碼會產生錯誤。

switch (caseSwitch)
{
    // The following switch section causes an error.
    case 1:
        Console.WriteLine("Case 1...");
        // Add a break or other jump statement here.
    case 2:
        Console.WriteLine("... and/or Case 2");
        break;
}

在 C# 中的要求是每個 switch 區段 (包括最後一個區段) 都是不可能執行到的。 雖然使用跳躍陳述式通常可以滿足此要求,但在下列情況下也是有效的,因為無法到達陳述式清單的結尾。

case 4:
    while (true)
        Console.WriteLine("Endless looping. . . .");

下列範例說明 switch 陳述式的需求和功能。

class Program
{
    static void Main(string[] args)
    {
        int switchExpression = 3;
        switch (switchExpression)
        {
            // A switch section can have more than one case label.
            case 0:
            case 1:
                Console.WriteLine("Case 0 or 1");
                // Most switch sections contain a jump statement, such as
                // a break, goto, or return. The end of the statement list
                // must be unreachable.
                break;
            case 2:
                Console.WriteLine("Case 2");
                break;
                // The following line causes a warning.
                Console.WriteLine("Unreachable code");
            // 7 - 4 in the following line evaluates to 3.
            case 7 - 4:
                Console.WriteLine("Case 3");
                break;
            // If the value of switchExpression is not 0, 1, 2, or 3, the
            // default case is executed.
            default:
                Console.WriteLine("Default case (optional)");
                // You cannot "fall through" any switch section, including
                // the last one.
                break;
        }
    }
}

在最後的範例中,將字串輸入轉換為整數變數 switchExp,用於 switch 運算式。 您也可以直接使用字串變數 str。 為了這樣做,您會變更案例標籤以指定字串值,如下列程式碼所示。

switch(str)
{
    case "1":
        // ...
    case "2":
        // ...
}
class SwitchTest
{
    static void Main()
    {
        Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
        Console.Write("Please enter your selection: ");
        string str = Console.ReadLine();
        int switchExp = int.Parse(str);
        int cost = 0;
        switch (switchExp)
        {
            case 1:
                cost += 25;
                break;
            case 2:
                cost += 25;
                goto case 1;
            case 3:
                cost += 50;
                goto case 1;
            default:
                Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
                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.
*/

C# 語言規格

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

請參閱

參考

C# 關鍵字

switch Statement (C++)

if-else (C# 參考)

概念

C# 程式設計手冊

其他資源

C# 參考

變更記錄

日期

記錄

原因

2010 年 9 月

新增「throw」至可結束 switch 區段的跳躍陳述式清單中。

客戶回函。