{
使用委托,将方法做为别一个方法的参数传递的例子(回调)
}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TDelegateClass=procedure(msg:string) of object;//定义一个委托
TDelegateClassArray=array[0..1] of TDelegateClass;
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
procedure UserMethod(msg:string);//委托指定的用户自定义方法
procedure UserMethod2(msg:string);//委托指定的用户自定义方法2
procedure doDelegate(Delegate:TDelegateClass;msg:string);//如果委托实例存在,就执行委托
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.doDelegate(Delegate:TDelegateClass;msg:string);
begin
if Assigned(Delegate) then
Delegate(msg);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
doDelegate(UserMethod,'test');//调用委托处理程序,显示test信息
end;
procedure TForm1.UserMethod(msg: string);
begin
showmessage(msg);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
test:TDelegateClassArray;
begin
test[0]:=UserMethod;
test[1]:=UserMethod2;
doDelegate(test[0],'test');
doDelegate(test[1],'test');
end;
procedure TForm1.UserMethod2(msg: string);
begin
showmessage('这是第二个方法');
end;
end.
--
Anony
专注的力量成就梦想
转自:http://anony3721.blog.163.com/blog/static/5119742010731104255351/
--------------------------------------------------------------------------------