if / else vs三元运算符 [英] if/else vs ternary operator
本文介绍了if / else vs三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑到评估时间,以下是两个相当的?
Considering the evaluation time, are following two equivalent?
if(condition1)
{
//code1
}
else
{
//code2
}
condition1?代码1:代码2
或者它们只是语法不同
推荐答案
区别在于后一站可用于根据条件返回值。
The difference is that the latter station can be used to return a value based on a condition.
例如,如果您有以下声明:
For example, if you have a following statement:
if (SomeCondition())
{
text = "Yes";
}
else
{
text = "No";
}
使用三元运算符,您将写:
Using a ternary operator, you will write:
text = SomeCondition() ? "Yes" : "No";
注意第一个示例如何根据条件执行语句,而第二个根据条件返回值。
Note how the first example executes a statement based on a condition, while the second one returns a value based on a condition.
这篇关于if / else vs三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文