C# - 三元运算符 ?:
本文关键字:三元 运算符 | 更新日期: 2023-09-12 17:38:57
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 is greater than 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 is less than y因此,三元运算符是if else
语句的缩写形式。上面的示例可以使用if else
条件重写,如下所示。
int x = 10, y = 100;
if (x > y)
Console.WriteLine("x is greater than y");
else
Console.WriteLine("x is less than y");
输出:
x is greater than 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);