要弄清楚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為類方法)的原因!
要了解更多請訪問:http://blog.csdn.net/rznice/article/details/6189094
接下來是兩種回調方式:
第一種是看萬一博客中的回調方式:http://www.cnblogs.com/del/archive/2008/01/15/1039476.html
第二種方式是我所需要的回調方式(兩個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.
還有很多值得深究的,還望多多指教...