Delphi 回调函数及property的使用

时间:2022-04-29 07:13:36

要弄清楚Delphi中的回调,首先要弄清楚:

delphi中经常见到的以下两种定义

Type

TMouseProc = procedure (X,Y:integer);

TMouseEvent = procedure (X,Y:integer) of Object;

两者样子差不多但实际意义却不一样,

TMouseProc只是单一的函数指针类型;

TMouseEvent是对象的函数指针,也就是对象/类的函数/方法

区别在于类方法存在一个隐藏参数self,也就是说两者形参不一样,所以不能相互转换。

这也就是为什么delphi中可以这样赋值 button1.onClick:=button2.onClick;

却不能这样赋值 button1.onclick=buttonclick; (buttonclick为本地函数,button2.onclick为类方法)的原因!

要了解更多请访问:

接下来是两种回调方式:

第一种是看万一博客中的回调方式:

第二种方式是我所需要的回调方式(两个Unit之间设置回调函数):

unit PropertyUseUnit;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type

TOnUserInfoShow = function(userName: string; userAge: Integer): Boolean of object;
// 定义事件模型中的回调函数原型

TUserInfo = class
private
FName: string;
FAge: Integer;
FOnUserInfoShow: TOnUserInfoShow;

procedure FSetAge(theAge: Integer);
public
property Name: string read FName; // 只读属性(私有变量)
property Age: Integer read FAge write FSetAge; // 读写属性(私有变量,私有方法)

property OnUserInfoShow: TOnUserInfoShow read FOnUserInfoShow
write FOnUserInfoShow; // 事件模型回调函数

constructor Create;
end;

TPropertyForm = class(TForm)
btnRead: TButton;
btnRW: TButton;
btnCallBck: TButton;
mmoText: TMemo;
procedure btnReadClick(Sender: TObject);
procedure btnRWClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnCallBckClick(Sender: TObject);
private
theUserInfo: TUserInfo;
function UserInfoShow(name: string; Age: Integer):Boolean;
{ Private declarations }
public
{ Public declarations }
end;

var
PropertyForm: TPropertyForm;

implementation

{$R *.dfm}
{ TPropertyForm }

procedure TPropertyForm.btnCallBckClick(Sender: TObject);
begin
Self.theUserInfo.OnUserInfoShow(Self.theUserInfo.name, Self.theUserInfo.Age);
end;

procedure TPropertyForm.btnReadClick(Sender: TObject);
begin
Self.mmoText.Lines.Add(‘读取只读属性姓名:‘ + Self.theUserInfo.name);
end;

procedure TPropertyForm.btnRWClick(Sender: TObject);
begin
Self.mmoText.Lines.Add(‘修改前的读写属性年龄为:‘ + inttostr(Self.theUserInfo.Age));
Self.theUserInfo.Age := 30;
Self.mmoText.Lines.Add(‘修改后的读写属性年龄为:‘ + inttostr(Self.theUserInfo.Age));
end;

procedure TPropertyForm.FormCreate(Sender: TObject);
begin
Self.mmoText.Color := clBlack;
Self.mmoText.Font.Color := clGreen;
theUserInfo := TUserInfo.Create;
Self.theUserInfo.OnUserInfoShow := Self.UserInfoShow;
end;

function TPropertyForm.UserInfoShow(name: string; Age: Integer):Boolean;
begin
Self.mmoText.Lines.Add(‘用户姓名为:‘ + Self.theUserInfo.name);
Self.mmoText.Lines.Add(‘用户年龄为:‘ + inttostr(Self.theUserInfo.Age));
Result:= True;
end;

{ TUserInfo }

constructor TUserInfo.Create;
begin
Self.FName := ‘Terry‘;
Self.FAge := 20;
end;

procedure TUserInfo.FSetAge(theAge: Integer);
begin
Self.FAge := theAge;
end;

end.

还有很多值得深究的,还望多多指教...

Delphi 回调函数及property的使用