class helper 可能是从 Delphi 2007 增加的新语法,
Txxx = class helper for T... {T... 表示已存在的类}
{可以替换已存在的方法}
{也可以有新的方法、成员}
end;
//这之后再使用 T... 类及其子孙类时, 都会优先使用 Txxx 的修改.
例一:
unit Unit1;
interface
uses
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: string;
end;
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;
interface
uses
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.
标签:...,func1,end,string,helper,TMyClassHelper,TMyClass,class From: https://www.cnblogs.com/lucken2000/p/17377483.html