C# - 三元运算符 ?
更新于:
C# 包含一个决策运算符 ?:
,它被称为条件运算符或三元运算符。它是 if else 条件的简写形式。
语法
condition ? statement 1 : statement 2
三元运算符以布尔条件开始。如果该条件评估为 true,则它将执行 ?
后的第一个语句,否则将执行 :
后的第二个语句。
以下示例演示了三元运算符。
示例:三元运算符
int x = 20, y = 10;
var result = x > y ? "x is greater than y" : "x is less than y";
Console.WriteLine(result);
输出
x 大于 y上面,条件表达式 x > y
返回 true,因此将执行 ?
后的第一个语句。
以下执行第二个语句。
示例:三元运算符
int x = 10, y = 100;
var result = x > y ? "x is greater than y" : "x is less than y";
Console.WriteLine(result);
输出
x 小于 y因此,三元运算符是 if else
语句的简写形式。上面的示例可以使用 if else
条件重写,如下所示。
示例:三元运算符替换 if 语句
int x = 10, y = 100;
if (x > y)
Console.WriteLine("x is greater than y");
else
Console.WriteLine("x is less than y");
输出
x 大于 y嵌套三元运算符
通过将条件表达式作为第二个语句包含在内,可以实现嵌套三元运算符。
示例:嵌套 ?
int x = 10, y = 100;
string result = x > y ? "x is greater than y" :
x < y ? "x is less than y" :
x == y ? "x is equal to y" : "No result";
Console.WriteLine(result);
三元运算符是右结合的。表达式 a ? b : c ? d : e
被评估为 a ? b : (c ? d : e)
,而不是 (a ? b : c) ? d : e
。
示例:嵌套 ?
var x = 2, y = 10;
var result = x * 3 > y ? x : y > z? y : z;
Console.WriteLine(result);