if/else vs 三元运算符 [英] if/else vs ternary operator
本文介绍了if/else vs 三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑到评估时间,以下两个是等价的吗?
Considering the evaluation time, are following two equivalent?
if(condition1)
{
//code1
}
else
{
//code2
}
<代码>条件 1 ?代码1:代码2
或者它们只是在语法上不同?
Or they are just syntactically different?
推荐答案
区别在于后一个站可以根据条件返回一个值.
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屋!
查看全文