Mar*_*rko 2 c# if-statement ternary-operator conditional-operator
可能重复:
使用条件?:(三元)运算符的好处条件运算符
是否缓慢?
大家好,
关于if/else语句的不同,我有一个非常简单的问题.
除了编写更少的代码之外,使用条件运算符而不是完整的if/else语句还有其他好处吗?
是否有性能提升,编译代码减少,或者在使用时有什么好处?
感谢您的帮助
马尔科
不要专注于编写更少的代码......专注于最终具有更高可读性的代码.
有时if声明会更具可读性.有时条件运算符更具可读性.在计算一个逻辑值的不同方式(例如基于客户年龄的折扣)方面,我喜欢条件运算符.我不喜欢以复杂的方式使用它 - 使用完整的if/else并没有任何问题.
值得记住null-coalescing运算符...所以代替:
string shipTo = customer.ShippingAddress != null
? customer.ShippingAddress : customer.BillingAddress;
Run Code Online (Sandbox Code Playgroud)
您可以使用
string shipTo = customer.ShippingAddress ?? customer.BillingAddress;
Run Code Online (Sandbox Code Playgroud)
同样,它仅在某些情况下有用 - 但在这些情况下它非常方便.