1 {
2 使用委托,将方法做为别一个方法的参数传递的例子(回调) 3 } 4 unit Unit1; 5 6 interface 7 8 uses 9 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 10 Dialogs, StdCtrls; 11 12 type 13 TDelegateClass=procedure(msg:string) of object;//定义一个委托 14 TDelegateClassArray=array[0..1] of TDelegateClass; 15 TForm1 = class(TForm) 16 Button1: TButton; 17 Button2: TButton; 18 procedure Button1Click(Sender: TObject); 19 procedure Button2Click(Sender: TObject); 20 private 21 { Private declarations } 22 procedure UserMethod(msg:string);//委托指定的用户自定义方法 23 procedure UserMethod2(msg:string);//委托指定的用户自定义方法2 24 procedure doDelegate(Delegate:TDelegateClass;msg:string);//如果委托实例存在,就执行委托 25 public 26 { Public declarations } 27 end; 28 29 var 30 Form1: TForm1; 31 32 implementation 33 34 {$R *.dfm} 35 36 { TForm1 } 37 38 procedure TForm1.doDelegate(Delegate:TDelegateClass;msg:string); 39 begin 40 if Assigned(Delegate) then 41 Delegate(msg); 42 end; 43 44 procedure TForm1.Button1Click(Sender: TObject); 45 begin 46 doDelegate(UserMethod,'test');//调用委托处理程序,显示test信息 47 end; 48 49 procedure TForm1.UserMethod(msg: string); 50 begin 51 showmessage(msg); 52 end; 53 54 procedure TForm1.Button2Click(Sender: TObject); 55 var 56 test:TDelegateClassArray; 57 begin 58 test[0]:=UserMethod; 59 test[1]:=UserMethod2; 60 doDelegate(test[0],'test'); 61 doDelegate(test[1],'test'); 62 end; 63 64 procedure TForm1.UserMethod2(msg: string); 65 begin 66 showmessage('这是第二个方法'); 67 end; 68 69 end. |