2011-03-09 62 views
20

可能重复:
Is there, or is there ever going to be, a conditional operator in Delphi?德尔福 - 相当于C#的三元运算符?

我明白德尔福可是没有三元操作符如C#。 即?:

那么如何最好地表示这个函数调用呢?那里最干净的方法是什么?

如果有任何可以使用的代码INSTEAD写一个单独的函数会很好吗?如果不是,它最有效和/或最干净的代码表示是什么?

+1

没有为 “*将*三元运算符” 没有这样的事。三元操作符是接受三个操作数的* any *操作符。你可能指的是一个特定的三元运算符,即'?:'。 – 2011-03-09 06:09:58

+0

感谢Mikael,投票结束。 – Simon 2011-03-09 06:26:39

+3

@Andreas,如果只有一个三元运算符,那么它就是*三元运算符。我们也可以通过它的名字 - 条件运算符来调用它。同样,只有一个人发布了关于这个问题的第一条评论。我们可以称他为发布关于这个问题的第一条评论的人,或者我们可以用他的名字叫Andreas。 – 2011-03-09 16:09:32

回答

35

当然你也可以使用

IfThen(SomeBooleanExpression, IfTrueReturnValue, IfFalseReturnValue) 

在返回值是数字(uses Math或串uses StrUtils)。但请注意,这将在所有情况下评估两个参数 - 没有懒惰评估,所以它不像C#中的?:运算符那样高效,只有右侧的操作数才被评估。

所以你不能做

y := IfThen(x <> 0, 1/x, 0) 

最好的办法是坚持用普通

if x <> 0 then y := 1/x else y := 0; 
+0

该死的希望避免我所有的小'如果然后elses':( – Simon 2011-03-09 06:24:05

+2

不知道这是否仍然如此,但使用IfThen的缺点是(/是),所有部分总是评估,你不能避免访问违规,就像你用“normal”if语句做的那样IE'if if(A)then X:= A.DoSome else X:='';' – 2011-03-09 08:05:39

+1

啊,现在看你提到懒惰评估,以0为例... – 2011-03-09 08:07:04

3

最近的是:

if (condition) then <staement> else <statement>; 

希望它能帮助。据我所知,Delphi中没有ternery操作符。

+0

对不起,有一个错字我不记得德尔福的ternery操作符 – 2011-03-09 06:16:39

2

从绝地尝试IFF:

function Iff(const Condition: Boolean; const TruePart: string; const FalsePart: string): string; overload; 
function Iff(const Condition: Boolean; const TruePart: Char; const FalsePart: Char): Char; overload; 
function Iff(const Condition: Boolean; const TruePart: Byte; const FalsePart: Byte): Byte; overload; 
function Iff(const Condition: Boolean; const TruePart: Integer; const FalsePart: Integer): Integer; overload; 
function Iff(const Condition: Boolean; const TruePart: Cardinal; const FalsePart: Cardinal): Cardinal; overload; 
function Iff(const Condition: Boolean; const TruePart: Float; const FalsePart: Float): Float; overload; 
function Iff(const Condition: Boolean; const TruePart: Boolean; const FalsePart: Boolean): Boolean; overload; 
function Iff(const Condition: Boolean; const TruePart: Pointer; const FalsePart: Pointer): Pointer; overload; 
function Iff(const Condition: Boolean; const TruePart: Int64; const FalsePart: Int64): Int64; overload; 
function Iff(const Condition: Boolean; const TruePart: Variant; const FalsePart: Variant): Variant; overload; 
+3

是的,这是RTL的IfThen函数的一个“扩展”版本,但它仍然遭受与'IfThen'功能相同的问题与'?:'相比。 – 2011-03-09 06:19:53

+0

是不一样的?: – Simon 2011-03-09 06:29:26