C# 中有三種常見的「問號」運算符,雖然長相相似,但用途截然不同。本文將逐一拆解 可空類型修飾符 (?)、空合併運算符 (??)、三元條件運算符 (?:) 的語法與實務應用。
? (Nullable Type)值類型(如 int、DateTime、struct)預設不能指派 null。加上 ? 後,即成為可空類型,允許表示「無值」狀態。
// 編譯錯誤:int 不能為 null
// int i = null;
// 正確:可空整數
int? nullableInt = null;
// 等同於
Nullable<int> nullableInt2 = null;
// 可空類型可正常參與運算,但結果可能為 null
int? a = 10;
int? b = null;
int? c = a + b; // c 為 null
本質: T? 是 System.Nullable<T> 的語法糖,編譯時會展開為泛型結構體。
?? (Null-coalescing Operator)用於為可空類型或參考類型提供預設值。語法:left ?? right。若 left 不為 null,回傳 left;否則回傳 right。
int? x = null;
int y = x ?? 100; // y = 100
int? z = 50;
int w = z ?? 100; // w = 50
// 串連用法:右結合,相當於 a ?? (b ?? c)
string result = a ?? b ?? c ?? "default";
常見於屬性初始化、參數預設值處理,避免冗長的 if (x == null) x = default; 判斷。
?: (Ternary Conditional Operator)唯一的三元運算符,語法:condition ? trueResult : falseResult。根據布林條件回傳兩個結果之一。
int score = 85;
string level = score >= 60 ? "及格" : "不及格"; // "及格"
// 巢狀使用(建議保持簡單)
string grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
| 運算符 | 名稱 | 用途 | 操作數個數 |
|---|---|---|---|
? | 可空類型修飾符 | 宣告可為 null 的值類型 | 1 (後綴) |
?? | 空合併運算符 | 提供 null 時的備選值 | 2 (二元) |
?: | 三元條件運算符 | 條件判斷回傳兩值之一 | 3 (三元) |
// 從設定檔讀取可空整數,若無則預設 10
int? configValue = GetConfigInt("MaxItems");
int maxItems = configValue ?? 10;
// 結合三元運算符決定訊息
string msg = maxItems > 0 ? $"上限 {maxItems}" : "無限制";
掌握三者差異,能寫出更精簡、表達力更強的 C# 程式碼。