首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# switch 語句深度解析:不可貫穿規則、模式比對、字串標籤與 goto case

     編輯:關於C#

核心語法與不可貫穿鐵律


switch (expression) {
    case constant1: statements; break;
    case constant2: case constant3: statements; break; // 群組 case
    default: statements; break;
}
  • 每個 case 必須以 break/return/throw/goto case 結束 (C# 強制,C/C++ 允許隱式貫穿)
  • default 最多一個,位置任意
  • 控制型別:整數、char、string、enum、可為 null 版本

為什麼禁止隱式貫穿?

C/C++ 經典 Bug:漏寫 break 導致非預期貫穿。C# 設計為預設安全,強制明確結束。若需貫穿,使用 goto case 使意圖顯性化。

明確貫穿:goto case / goto default


int total = 365;
switch (month) {
    case 1: total -= 31; goto case 2;
    case 2: total -= 28; goto case 3;
    case 3: total -= 31; goto case 4;
    case 4: total -= 30; goto case 5;
    case 5: total -= 31; goto case 6;
    case 6: total -= 30; goto case 7;
    case 7: total -= 31; goto case 8;
    case 8: total -= 31; goto case 9;
    case 9: total -= 30; goto case 10;
    case 10: total -= 31; goto case 11;
    case 11: total -= 30; goto case 12;
    case 12: total -= 31; goto default;
    default: total += day; break;
}

替代結束方式

任何不導致貫穿的結構皆可:


switch (i) {
    case 0: while (true) Foo(); // 無限迴圈不返回
    case 1: throw new ArgumentException(); // 拋出例外
    case 2: return; // 返回
    case 3: break;  // 標準
}

字串作為 case 標籤

C# 支援 string 控制型別與 case "text" (C/C++ 僅限整數/字元)。


string tooltip = GetButtonTooltip();
switch (tooltip) {
    case "OK": ShowMsg("Save and exit"); break;
    case "Retry": ShowMsg("Return and retry"); break;
    case "Abort": ShowMsg("Abort changes"); break;
    case "Help": ShowMsg("Get help"); break;
    default: ShowMsg("Unknown"); break;
}
  • 比較使用序數比較 (Ordinal),區分大小寫
  • case null: 合法,處理 null 參考

模式比對增強 (C# 7.0+)

型別模式


object obj = GetValue();
switch (obj) {
    case int i: Console.WriteLine($"Integer: {i}"); break;
    case string s: Console.WriteLine($"String: {s}"); break;
    case null: Console.WriteLine("Null"); break;
    default: Console.WriteLine("Other"); break;
}

When 守衛條件


switch (value) {
    case int i when i > 0: Console.WriteLine("Positive"); break;
    case int i when i < 0: Console.WriteLine("Negative"); break;
    case int i: Console.WriteLine("Zero"); break;
}

Switch 運算式 (C# 8.0+)


// 運算式主體,自動返回值
var result = shape switch {
    Rectangle r => r.Width * r.Height,
    Circle c => Math.PI * c.Radius * c.Radius,
    Triangle t => 0.5 * t.Base * t.Height,
    _ => 0
};

// 屬性模式
var category = person switch {
    { Age: >= 65 } => "Senior",
    { Age: >= 18, IsEmployed: true } => "Working Adult",
    { Age: >= 18 } => "Adult",
    _ => "Minor"
};

編譯器優化

  • 整數 switch 可能編譯為 跳躍表 (Jump Table) O(1) 分派
  • string switch 通常編譯為雜湊表或二元搜尋樹
  • 案例數較少時退化為 if-else 鏈

總結

C# switch 以「不可隱式貫穿」確保安全,支援 goto case 明確貫穿、string 標籤、型別/屬性/關係模式比對、Switch 運算式函數式風格。掌握模式比對語法,能將複雜條件邏輯轉化為清晰可維護的程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved