條件運算子 ?: (也稱為三元條件運算子) 會評估布林運算式,並且根據布林運算式評估為 true 或 false,傳回兩個運算式其中之一的結果,如下列範例所示:
string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ? "Cold." : "Perfect!";
Console.WriteLine(GetWeatherDisplay(15)); // output: Cold.
Console.WriteLine(GetWeatherDisplay(27)); // output: Perfect!
如上述範例所示,條件運算子的語法如下所示:
condition ? consequent : alternative
C# 語言參考資料記錄了 C# 語言最新版本。 同時也包含即將推出語言版本公開預覽功能的初步文件。
文件中標示了語言最近三個版本或目前公開預覽版中首次引入的任何功能。
提示
欲查詢某功能何時首次在 C# 中引入,請參閱 C# 語言版本歷史的條目。
condition 運算式必須評估為 true 或 false。 如果 condition 評估為 true,就會接著評估 consequent 運算式,且其結果會成為運算的結果。 如果 condition 評估為 false,就會接著評估 alternative 運算式,且其結果會成為運算的結果。 系統只會評估 consequent 或 alternative。 條件運算式為目標型別。 也就是說,如果已知條件運算式的目標型別,則 consequent 和 alternative 的型別必須隱含轉換成目標型別,如下列範例所示:
var rand = new Random();
var condition = rand.NextDouble() > 0.5;
int? x = condition ? 12 : null;
IEnumerable<int> xs = x is null ? new List<int>() { 0, 1 } : new int[] { 2, 3 };
例如,如果條件運算式的目標型別未知 (例如,您使用 var 關鍵字) 或 consequent 的型別時,而且 alternative 必須相同,或者必須有從某個型別到另一個型別的隱含轉換:
var rand = new Random();
var condition = rand.NextDouble() > 0.5;
var x = condition ? 12 : (int?)null;
條件運算子是右向關聯運算子,亦即,以下形式的運算式
a ? b : c ? d : e
評估為
a ? b : (c ? d : e)
提示
您可以使用下列助憶鍵裝置來記住條件運算子的評估方式:
is this condition true ? yes : no
條件 ref 運算式
條件 ref 運算式會有條件地傳回變數參考,如下列範例所示:
int[] smallArray = {1, 2, 3, 4, 5};
int[] largeArray = {10, 20, 30, 40, 50};
int index = 7;
ref int refValue = ref ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]);
refValue = 0;
index = 2;
((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]) = 100;
Console.WriteLine(string.Join(" ", smallArray));
Console.WriteLine(string.Join(" ", largeArray));
// Output:
// 1 2 100 4 5
// 10 20 0 40 50
你可以 ref 指派 條件參考表達式的結果。 可將其用作參考回傳,或以 ref、 out、 inref readonly 或方法參數傳遞。 您也可以指派給條件 ref 運算式的結果,如上述範例所示。
條件 ref 運算式的語法如下:
condition ? ref consequent : ref alternative
與條件運算子相同,條件 ref 運算式只會評估兩個運算式其中之一:consequent 或 alternative。
在條件 ref 運算式中,consequent 與 alternative 的型別必須相同。 條件式 ref 運算式不是目標型別。
條件運算子和 if 陳述式
使用條件運算子代替陳述if句,可以讓程式碼更簡潔,當你需要條件計算值時。 下列範例示範兩種將整數分類為負值或非負值的方法:
int input = new Random().Next(-5, 5);
string classify;
if (input >= 0)
{
classify = "nonnegative";
}
else
{
classify = "negative";
}
classify = (input >= 0) ? "nonnegative" : "negative";
運算子是否可多載
使用者定義型別無法多載條件式運算子。
C# 語言規格
較新版本功能的規格如下: