我经常发现自己声明一个简单的过程类型
TMessageProc = procedure(const AMsg: String);
在德尔福。目的是允许将回调过程传递给处理函数,以便它们可以更新用户界面而无需了解用户界面。
这肯定是 Delphi 编程中的常见范例。在我可以用于此目的的常用单元之一中是否存在标准过程类型声明?不幸的是,使用我自己的方法,我在项目之间命名或声明类型的方式并不完全一致。
最佳答案
“常见的Delphi范例”是事件(事件处理程序)。例如,你可以写
type
TMessageProc = procedure(const AMsg: String);
procedure DoSomething(OnProgress: TMessageProc);
begin
// ...
if Assigned(OnProgress) then OnProgress('123');
// ...
end;
通常,Delphi 中的事件都是作为方法实现的,因此上述示例的标准 Delphi 代码是:
type
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure ShowProgress(const AMsg: String);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TMessageProc = procedure(const AMsg: String) of object; // declare event type
procedure DoSomething(OnProgress: TMessageProc);
begin
// ...
if Assigned(OnProgress) then OnProgress('123'); // trigger event
// ...
end;
procedure TForm1.ShowProgress(const AMsg: String); // event handler
begin
Label1.Caption:= AMsg;
Application.ProcessMessages;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
DoSomething(ShowProgress);
end;
声明您的个人事件类型没有任何问题,但您肯定可以在 VCL 中找到标准事件。例如,classes.pas 单元包含声明
TGetStrProc = procedure(const S: string) of object;
关于delphi - Delphi 中消息传递过程的现有过程类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2308148/