Delphi - 相当于C#的三元运算符? [英] Delphi - Equivalent to C#'s ternary operator?
问题描述
我明白,Delphi没有C#中的三元运算符。
即?:
I understand Delphi doesnt have the ternary operator as in C#.
i.e. ?:
那么最好的代表这个函数调用?那里最干净的方法是什么?
So how best to represent this function call? Whats the cleanest method out there?
如果有任何代码可以使用INSTEAD编写单独的函数会很好吗?如果没有,最有效和最干净的代码代码是什么?
Would be very nice if there is any code out there that can be used INSTEAD of writing a separate function? If not, whats the most efficient and/or cleanest code representation of it?
推荐答案
当然可以使用
IfThen(SomeBooleanExpression, IfTrueReturnValue, IfFalseReturnValue)
其中返回值为数字(使用Math
)或字符串(使用StrUtils
)。但是请注意,这将在所有情况下评估两个参数 - 没有懒惰的评估,所以它不如C#中的?:
运算符那么有效,只有右边操作数被评估。
where the return values are numeric (uses Math
) or string (uses StrUtils
). But notice that this will evaluate both arguments in all cases -- there is no lazy evaluation, so it is not as efficient as the ?:
operator in C#, where only the right operand is evaluated.
所以你不能做
y := IfThen(x <> 0, 1/x, 0)
最好的事情是坚持与普通
The best thing is to stick with an ordinary
if x <> 0 then y := 1/x else y := 0;
这篇关于Delphi - 相当于C#的三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!