?:運算子 - 三元條件運算子

條件運算子 ?: (也稱為三元條件運算子) 會評估布林運算式,並且根據布林運算式評估為 truefalse,傳回兩個運算式其中之一的結果,如下列範例所示:

string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ? "Cold." : "Perfect!";

Console.WriteLine(GetWeatherDisplay(15));  // output: Cold.
Console.WriteLine(GetWeatherDisplay(27));  // output: Perfect!

如上述範例所示,條件運算子的語法如下所示:

condition ? consequent : alternative

condition 運算式必須評估為 truefalse。 如果 condition 評估為 true,就會接著評估 consequent 運算式,且其結果會成為運算的結果。 如果 condition 評估為 false,就會接著評估 alternative 運算式,且其結果會成為運算的結果。 系統只會評估 consequentalternative。 條件運算式為目標型別。 也就是說,如果已知條件運算式的目標型別,則 consequentalternative 的型別必須隱含轉換成目標型別,如下列範例所示:

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 運算式的結果、使用它作為參考傳回,或將它當作 refoutinref readonly方法參數傳遞。 您也可以指派給條件 ref 運算式的結果,如上述範例所示。

條件 ref 運算式的語法如下:

condition ? ref consequent : ref alternative

與條件運算子相同,條件 ref 運算式只會評估兩個運算式其中之一:consequentalternative

在條件 ref 運算式中,consequentalternative 的型別必須相同。 條件式 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# 語言規格

如需詳細資訊,請參閱 C# 語言規格條件運算子一節。

較新版本功能的規格如下:

另請參閱