C# 简写 If...Else
简写 If...Else(三元运算符)
还有一种简写形式的 if else,被称为三元运算符,因为它由三个操作数组成。
它可以用来将多行代码替换为单行代码。它经常被用来替换简单的 if else 语句:
语法
variable = (condition) ? expressionTrue : expressionFalse;
这样就不需要写成:
实例
int time = 20;
if (time < 18)
{
Console.WriteLine("日安");
}
else
{
Console.WriteLine("晚安");
}
你可以简单地写成:
实例
int time = 20; string result = (time < 18) ? "日安" : "晚安"; Console.WriteLine(result);