问题
I can write
if(Model.DecisionReason != null && Model.DecisionReason.Length > 35)
return Model.DecisionReason.Substring(0, 32) + "...";
else
return Model.DecisionReason;
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;
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)?
回答1:
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.
来源:https://stackoverflow.com/questions/10128110/is-there-a-way-to-short-circuit-a-ternary-operation