问题描述
可能显示的文件:结果
的结果
的
大家好,
我有关于if / else语句不同的一个非常简单的问题。
I've got a pretty simple question regarding the different if/else statements.
除了从写更少的代码,是否有使用条件运算符,而不是完整的任何其他好处if / else语句?
Apart from writing less code, are there any other benefits for using the conditional operator as opposed to the full if/else statement?
是否有性能提升,更少的编译代码,或其他任何将使用它时有什么好处?
Is there a performance increase, less compiled code, or anything else that would benefit me when using it?
感谢您的帮助。
马尔科
推荐答案
不要专注于的写的更少的代码...专注于你的代码与被越来越结束的阅读的
Don't focus on writing less code... focus on the code you end up with being more readable.
有时一个如果
语句会更可读。有时,有条件的运营商将更具可读性。我喜欢在案件的条件算哪里它是有道理的,在计算一个逻辑值(例如打折,根据客户的年龄)不同的方式计算。我不喜欢但令人费解的方式使用它 - 没有什么错的if / else在有意义使用全
Sometimes an if
statement will be more readable. Sometimes the conditional operator will be more readable. I like the conditional operator in cases where it makes sense, in terms of different ways of calculating one logical value (e.g. a discount, based on the age of a customer). I don't like using it in convoluted ways though - there's nothing wrong with using a full if/else where it makes sense.
这是值得记住的空合并运算符太...所以不是:
It's worth remembering the null-coalescing operator too... so instead of:
string shipTo = customer.ShippingAddress != null
? customer.ShippingAddress : customer.BillingAddress;
您可以使用
string shipTo = customer.ShippingAddress ?? customer.BillingAddress;
再次,它只有在某些情况下非常有用 - 但在这种情况下它真的很方便。
Again, it's only useful in certain situations - but in those cases it's really handy.
这篇关于全if / else语句与条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!