条件运算符 (?:
) 也被称为三元条件运算符,用于计算布尔表达式,并根据布尔表达式的计算结果为 true
还是 false
来返回两个表达式中的一个结果。
条件运算符的语法如下所示:
C#复制
condition ? consequent : alternative
condition
表达式的计算结果必须为 true
或 false
。 若 condition
的计算结果为 true
,将计算 consequent
,其结果成为运算结果。 若 condition
的计算结果为 false
,将计算 alternative
,其结果成为运算结果。 只会计算 consequent
或 alternative
。
从 C# 9.0 开始,条件表达式由目标确定类型。 也就是说,如果条件表达式的目标类型是已知的,则 consequent
和 alternative
的类型必须可隐式转换为目标类型,如以下示例所示:
C#复制
var rand = new Random();
var condition = rand.NextDouble() > 0.5;
int? x = condition ? 12 : null;
可以使用以下助记键设备记住条件运算符的计算方式:
text复制
is this condition true ? yes : no
ref 条件表达式
从 C# 7.2 开始,可通过 ref 条件表达式有条件地分配 ref local 或 ref readonly local 变量。 还可以使用 ref 条件表达式作为引用返回值或 ref
方法参数。
ref 条件表达式的语法如下所示:
C#复制
condition ? ref consequent : ref alternative
ref 条件表达式与原始的条件运算符相似,仅计算两个表达式其中之一:consequent
或 alternative
。
在 ref 条件表达式中,consequent
和 alternative
的类型必须相同。 ref 条件表达式不由目标确定类型。
https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/operators/conditional-operator