條件運算子 ?: 是 C# 唯一的三元運算子,語法:condition ? consequent : alternative。
condition(必須為 bool)。true → 評估 consequent,結果為其值。false → 評估 alternative,結果為其值。consequent 隱含轉換 → alternative,無反向 → alternative 型別。alternative 隱含轉換 → consequent,無反向 → consequent 型別。
int? a = true ? 1 : 2; // int (兩邊皆 int)
double b = true ? 1 : 2.0; // double (int→double 隱含)
var c = true ? 1 : "text"; // 錯誤:無隱含轉換
var d = true ? (object)1 : "text"; // object (兩邊皆→object)
a ? b : c ? d : e 等價 a ? b : (c ? d : e)。建議加括號明確。
?:。if-else 區塊,可讀性更高。?:(難除錯、難閱讀)。