我了解三元运算符的标准用法..
string message = hasError=="Y" ? "There's an error!" : "Everything seems fine...";
但是如何在子表达式中添加 OR ..
if((hasError=="Y")||(seemsfine=="N")){
message="There's an error!";
}else{message="Everything seems fine...";
}
真诚感谢任何帮助
谢谢
最佳答案
你可以这样做
string message = hasError == "Y" || seemsfine == "N" ? "There's an error!" : "Everything seems fine...";
没有太大区别。这是因为 C# 中的三元运算符非常方便!
最终,重要的是整个表达式的结果(即 hasError == "Y"|| suggestine == "N"
),而不是有多少个条件。如果您愿意,您也可以添加所有其他条件,只要整个表达式返回 true
,那么它将把第一个元素(:
的左侧)分配给变量,并且当整个表达式为 false
它将第二个元素(:
的右侧)分配给变量
三元运算符与 if-else 语句完全等效,其 block 只是为单个变量赋值。
因此,
if (a1 == 0 || a2 > 5 || a3 <= -7)
b = 1;
else
b = 2;
完全等同于
b = a1 == 0 || a2 > 5 || a3 <= -7 ? 1 : 2; //note that there is no bracket here, but it is equivalent to if-else statement with bracket
当要分配多个单个变量时,等效的中断。
if (a1 >= 0)
b = 2;
else
c = 3; //notice the variable difference, you cannot use ternary operator anymore.
只要不妨碍代码的可读性,你甚至可以像这样放置多个三元运算符
b = a1 > 0 && a2 < 0 ? 1 : (a3 < 5 ? 2 : 3);
这相当于
if (a1 > 0 && a2 < 0)
b = 1;
else if (a3 < 5)
b = 2;
else
b = 3;
关于c# - C# 子表达式中 OR 的三元运算符用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34472761/