2011-03-09 63 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