【问题标题】:Delphi - Equivalent to C#'s ternary operator? [duplicate]Delphi - 相当于 C# 的三元运算符? [复制]
【发布时间】:2011-07-11 15:35:16
【问题描述】:

可能重复:
Is there, or is there ever going to be, a conditional operator in Delphi?

我知道 Delphi 没有 C# 中的三元运算符。 即?:

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

如果有任何代码可以用来代替编写单独的函数,那会很好吗?如果不是,那么最有效和/或最简洁的代码表示形式是什么?

【问题讨论】:

  • 不存在“the 三元运算符”。三元运算符是接受三个操作数的 any 运算符。您可能指的是特定的三元运算符,即?:
  • 感谢 Mikael,投票结束。
  • @Andreas,如果只有一个三元运算符,那么它就是 the 三元运算符。我们也可以通过它的名字来称呼它,条件运算符。同样,只有一个人发表了关于这个问题的第一条评论。我们可以称他为对这个问题发表第一条评论的人,也可以直呼他的名字 Andreas。
  • 要回答“是否会成为一部分”,我的猜测是没有,不会有。这不是“Pascal-y”。
  • @Rob:是的,你是对的,当然。

标签: delphi operators ternary-operator


【解决方案1】:

最接近三元运算符的是:

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

据我所知,Delphi 中没有三元运算符。

【讨论】:

  • 对不起,有一个错字。我不记得 Delphi 中的三元运算符。
【解决方案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】:

当然可以

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;

【讨论】:

  • 该死的希望能避开我所有的小if then elses :(
  • 不知道是否仍然如此,但使用 IfThen 的缺点是(/是)总是评估所有部分,并且您无法像使用“正常”那样避免访问冲突" if 语句。即if Assigned(A) then X := A.DoSome else X := '';
  • 啊,现在看到你提到了惰性求值,但以除以零为例......
  • 如果两个值代替表达式(匿名函数)可以进行短路评估
猜你喜欢
  • 2015-02-03
  • 2011-03-11
  • 2011-06-05
  • 1970-01-01
  • 2014-04-20
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
相关资源
最近更新 更多