一、什么是C#三元表达式
C#三元表达式是一种简短的if-else语句的简写形式,语法为condition ? true_expression : false_expression
。其中,condition代表一个条件表达式,true_expression代表当条件为真时的表达式,false_expression代表当条件为假时的表达式。
二、C#三元表达式的用法
使用C#三元表达式可以简化复杂的if-else语句的书写,使代码更加简洁,提高代码的可读性。 举个例子,如下面这段代码:
int a = 5;
int b;
if (a > 10)
{
b = 1;
}
else
{
b = 2;
}
可以使用三元表达式改写成:
int a = 5;
int b = a > 10 ? 1 : 2;
使用三元表达式还可以嵌套使用,如下面这段代码:
int a = 5;
int b;
if (a >= 0)
{
if (a < 10)
{
b = 1;
}
else
{
b = 2;
}
}
else
{
b = 0;
}
可以使用三元表达式改写成:
int a = 5;
int b = a >= 0 ? (a < 10 ? 1 : 2) : 0;
三、C#三元表达式的示例代码
1、使用三元表达式改写if-else语句
int x = 5;
int y = x < 10 ? 1 : 2;
Console.WriteLine(y); // 输出结果为1
2、使用三元表达式判断字符串为空
在C#中,判断字符串是否为空,可以使用string.IsNullOrEmpty()方法,也可以使用三元表达式。
string str = "";
bool isNull = string.IsNullOrEmpty(str) ? true : false;
Console.WriteLine(isNull); // 输出结果为true
3、使用三元表达式判断是否为偶数
int num = 5;
string result = num % 2 == 0 ? "偶数" : "奇数";
Console.WriteLine(result); // 输出结果为奇数
4、使用三元表达式判断年龄是否大于等于18岁
int age = 20;
bool isAdult = age >= 18 ? true : false;
Console.WriteLine(isAdult); // 输出结果为true
5、使用三元表达式判断两个数的大小关系
int a = 10;
int b = 5;
string result = a > b ? "a大于b" : a == b ? "a等于b" : "a小于b";
Console.WriteLine(result); // 输出结果为a大于b