Delphi新语法和ifthen的扩展联想

时间:2023-03-09 17:24:22
Delphi新语法和ifthen的扩展联想

Delphi之前已经重载了好多个ifthen函数

Math单元

function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer = ): Integer; overload; inline; 

function IfThen(AValue: Boolean; const ATrue: Int64; const AFalse: Int64 = ): Int64; overload; inline; 

function IfThen(AValue: Boolean; const ATrue: UInt64; const AFalse: UInt64 = ): UInt64; overload; inline; 

function IfThen(AValue: Boolean; const ATrue: Single; const AFalse: Single = 0.0): Single; overload; inline;

 function IfThen(AValue: Boolean; const ATrue: Double; const AFalse: Double = 0.0): Double; overload; inline; 

function IfThen(AValue: Boolean; const ATrue: Extended; const AFalse: Extended = 0.0): Extended; overload; inline;

StrUtils单元

function IfThen(AValue: Boolean; const ATrue: string; AFalse: string = ”): string; overload; inline;

Delphi从2009之后增加了泛型,那么之前math,strutils单元的ifthen函数有很多种重载形式似乎就可以合并成一个单独的泛型函数了.

type  TExtFuns = class
class function IfThen<T>(AValue: Boolean; const ATrue, AFalse: T): T; inline;
end;
class function TExtFuns.IfThen<T>(AValue: Boolean; const ATrue, AFalse: T): T;
begin
if AValue then Result := ATrue else Result := AFalse;
end; //使用示例
var s : string; i : Integer;
// s := TExtFuns.IfThen(True, '条件成立', '条件不成立!');
i := TExtFuns.IfThen(GetTickCount > , , );

从XE3以后扩展了新的Helper语法,可以给任意类型增加扩展函数.就有更方便的技巧了.如下

TBoolHelper = record helper for Boolean
function IfThen<T>(const ATrue, AFalse: T): T; inline;
end; function TBoolHelper.IfThen<T>(const ATrue, AFalse: T): T;
begin
if self then Result := ATrue else Result := AFalse;
end; //使用
var s : string; i : Integer;
// s := True.IfThen('a','b');
i := (gettickcount >).IfThen(, );
//是不是很爽,方便程度不亚于C语言族系的?:语法吧.
end;

XE3之后的SysUtils单元里面内置了TBooleanHelper,TByteBoolHelper,TWordBoolHelper,TLongBoolHelper四个布尔类型的Helper,那么如果易博龙肯把ifthen集成到这四个辅助类上我们用起来就会更方便.只可惜XE5都出了还是没集成在里面。