打开APP
userphoto
未登录

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

开通VIP
关于 class helper for ... 语法

class helper 可能是从 Delphi 2007 增加的新语法, 因为感觉不太实用, 直到今天才测试了一下.

试过之后才知道: 挺有意思的! 基本功能就是修改已存在的类.

Txxx = class helper for T... {T... 表示已存在的类}  {可以替换已存在的方法}  {也可以有新的方法、成员}end;//这之后再使用 T... 类及其子孙类时, 都会优先使用 Txxx 的修改.

例一:
unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls;type  TForm1 = class(TForm)    Button1: TButton;    procedure Button1Click(Sender: TObject);  end;  TMyClass = class    function func1: string;    function func2: stringend;  TMyClassHelper = class helper for TMyClass    function func1: string; {将把 TMyClass 的同名方法替换掉}    function func3: string; {将为 TMyClass 及其子类增加这个方法}  end;var  Form1: TForm1;implementation{$R *.dfm}{ TMyClass }function TMyClass.func1: string;begin  Result := 'TMyClass.func1';end;function TMyClass.func2: string;begin  Result := 'TMyClass.func2';end;{ TMyClassHelper }function TMyClassHelper.func1: string;begin  Result := 'TMyClassHelper.func1';end;function TMyClassHelper.func3: string;begin  Result := 'TMyClassHelper.func3';end;//测试procedure TForm1.Button1Click(Sender: TObject);var  obj: TMyClass;begin  obj := TMyClass.Create;  ShowMessage(obj.func1); {TMyClassHelper.func1}  ShowMessage(obj.func2); {TMyClass.func2}  ShowMessage(obj.func3); {TMyClassHelper.func3}  obj.Free;end;end.

例二: 本例为 TControl 类增加了一个方法, 之后 TControl 及其所有子孙类就都拥有了这个方法.
unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls;type  TForm1 = class(TForm)    Button1: TButton;    procedure Button1Click(Sender: TObject);  end;  TMyClassHelper = class helper for TControl    procedure MyMsg;  end;var  Form1: TForm1;implementation{$R *.dfm}{ TMyClassHelper }procedure TMyClassHelper.MyMsg;begin  ShowMessageFmt('%s 的类名是 %s', [Name,ClassName]);end;//测试: 这里测试了当前窗体和当前按钮, 它们都是从 TControl 继承来的procedure TForm1.Button1Click(Sender: TObject);begin  Self.MyMsg;            {Form1 的类名是 TForm1}  TButton(Sender).MyMsg; {Button1 的类名是 TButton1}end;end.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Delphi 的接口
用 Delphi 学设计模式(一) 之简单工厂篇
call a function whose name is stored in a string in Delphi
ERP SYSTEM 开发指南(二)添加脚本支持
《Mastering Delphi 6》学习笔记之五
delphi基础开发技巧
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服