選擇結構核心類型
| 結構 | 適用場景 | 範例 |
| if-else | 布林條件、複雜邏輯、範圍判斷 | if (x > 0) ... else ... |
| switch | 離散值、多重分支、模式比對 | switch (c) { case 'A': ... } |
| 三元運算子 | 簡單條件賦值/回傳 | var r = x > 0 ? "P" : "N"; |
| 模式比對 | 型別檢查、解構、屬性判斷 | if (obj is int i) ... |
if-else 進階用法
// 巢狀 if-else 重構為 else-if 鏈
if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else grade = 'F';
// 複合條件:短路求值
if (user != null && user.IsActive && user.HasPermission("Admin")) {
GrantAccess();
}
// 模式比對增強 if (C# 7+)
if (input is int number) {
Console.WriteLine($"整數: {number}");
} else if (input is string text) {
Console.WriteLine($"字串: {text.Length} 字元");
}
// 宣告模式結合 when (C# 7+)
if (shape is Rectangle r when r.Width == r.Height) {
Console.WriteLine("正方形");
}
三元運算子與 Null 合併運算子
// 基本三元
string status = isOnline ? "上線" : "離線";
// 巢狀三元 (不建議超過兩層)
string level = score >= 90 ? "優" : score >= 60 ? "及格" : "不及格";
// Null 合併 ?? (C# 2+)
string name = user?.Name ?? "訪客";
// Null 合併指派 ??= (C# 8+)
cache ??= new Dictionary();
// 條件存取 ?. 結合 ??
int length = user?.Name?.Length ?? 0;
實務決策指南
需要根據型別分派?
├─ 是 → 模式比對 (is/switch)
└─ 否 → 分支數量?
├─ 2 個、簡單賦值 → 三元 / ??
├─ 3-5 個離散值 → switch
├─ 複雜範圍/複合條件 → if-else 鏈
└─ 大量分支/效能關鍵 → Dictionary/策略模式/查找表
常見反模式與重構
| 反模式 | 問題 | 重構方向 |
| 箭頭型程式碼 (深層巢狀 if) | 可讀性差、難測試 | 衛語句提早返回、策略模式 |
| 魔術數字散布條件 | 維護困難 | 常數/列舉/設定檔 |
| 重複條件判斷 | 效能浪費、邏輯不一致風險 | 提取變數/方法、規格模式 |
| switch 缺少 default | 新增 enum 值時無編譯警告 | 加上 default throw 或 _ case |






本文對應《叩響 C# 之門》第 4.4 節選擇結構教學內容