使用条件的好处:(三元)运算符 [英] Benefits of using the conditional ?: (ternary) operator

查看:266
本文介绍了使用条件的好处:(三元)运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好处和弊端的:相对于标准的if-else语句运营商?最明显的莫过于:

What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:

条件:?运营商


  • 短,直接价值的比较和作业打交道时更简洁

  • 似乎并不那么灵活的的if / else构造

  • Shorter and more concise when dealing with direct value comparisons and assignments
  • Doesn't seem to be as flexible as the if/else construct

标准的if / else


  • 可以应用在更多的情况下(如函数调用)

  • 往往过长

  • Can be applied to more situations (such as function calls)
  • Often are unnecessarily long

可读性似乎为每个根据该语句而不同。一小会儿后,第一次被暴露在:运营商,我花了一些时间来消化它究竟是如何工作的。你会建议使用它只要有可能,或者坚持的if / else因为我与许多非程序员工作的?

Readability seems to vary for each depending on the statement. For a little while after first being exposed to the ?: operator, it took me some time to digest exactly how it worked. Would you recommend using it wherever possible, or sticking to if/else given that I work with many non-programmers?

推荐答案

我基本上会建议使用它,只有当产生的语句是非常短,并重新presents过的if / else相当于简洁一个显著上升不牺牲可读性。

I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.

很好的例子:

int result = Check() ? 1 : 0;

错误的例子:

int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;

这篇关于使用条件的好处:(三元)运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆