?: 运算符 - 三元条件运算符

条件运算符 (?:) 也称为三元条件运算符,用于计算布尔表达式,并根据布尔表达式的计算结果为 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

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 关键字时)或 consequentalternative 的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换:

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# 语言规范条件运算符部分。

较新版本功能的规范如下:

另请参阅