Delphi - 相当于C#的三元运算符? [英] Delphi - Equivalent to C#'s ternary operator?

查看:214
本文介绍了Delphi - 相当于C#的三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我明白,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆