本文介绍了有没有办法使三元运算短路?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以写
if(Model.DecisionReason != null && Model.DecisionReason.Length > 35)
return Model.DecisionReason.Substring(0, 32) + "...";
else
return Model.DecisionReason;
和&&
的比较 if
会短路,从而防止 Model.DecisionReason
为null时发生异常。但是,如果我写
and the &&
comparison in the if
will short-circuit, preventing an exception if Model.DecisionReason
is null. However, if I write
return (Model.DecisionReason != null && Model.DecisionReason.Length > 35) ?
Model.DecisionReason.Substring(0, 32) + "..." :
Model.DecisionReason;
没有短路,我遇到了例外。有没有办法使其短路,或者我是否被迫将长度比较包裹在 if
检查是否为空或嵌套三元组中(不是最易读的) )?
There is no short-circuit and I hit the exception. Is there a way to make it to short-circuit, or am I forced to either wrap the length comparison in an if
check for the null or nest ternaries (not the most readable)?
推荐答案
您编写的两个代码示例都具有相同的行为。不是如果
发生短路,而是&&
表达式本身的核心组成部分。
Both of the code samples you wrote will have identical behavior. It's not the if
that's short circuiting but simply a core component of the &&
expression itself.
这篇关于有没有办法使三元运算短路?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!