打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Delphi新语法和ifthen的扩展联想. | 武稀松(wr960204)的博客

Delphi新语法和ifthen的扩展联想.

看看Delphi重载了多少个ifthen函数.
Math单元
function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer = 0): Integer; overload; inline;
function IfThen(AValue: Boolean; const ATrue: Int64; const AFalse: Int64 = 0): Int64; overload; inline;
function IfThen(AValue: Boolean; const ATrue: UInt64; const AFalse: UInt64 = 0): 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 > 1, 1, 2);

还有更便捷的办法,从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 >1).IfThen(1, 2);
//是不是很爽,方便程度不亚于C语言族系的?:语法吧.
end;

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

此条目发表在 Delphi, 未分类 分类目录。将固定链接加入收藏夹。

Delphi新语法和ifthen的扩展联想.》有 3 条评论

  1. tintinsoft 说:

    我七月给EMB提了建议,让他们提供完整的数据类型helper,包括 TDateTimeHelper,TVariantHelper,还有你的TArrayHelper,还有枚举值类型的helper,他们真的要做的话,估计编码+严格测试不到一周就完成!只可惜,,XE5没集成。。。。。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Delphi Math单元函数
DBGridEhToExcel(一个导出Excel非常快的类)
我对DELPHI写的几个基类型
【翻译】NativeXml帮助(三)
Delphi字符串函数大全
《Mastering Delphi 6》学习笔记之六
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服