CSDN博客

img lwjghhh

How to execute a method (procedure/function) by name

发表于2004/10/25 10:06:00  644人阅读

分类: DELPHI

Here's a simple trick to execute a Delphi object's method by name:

~~~~~~~~~~~~~~~~~~~~~~~~~
type
牋 TForm1 = class(TForm)
牋牋 Button1: TButton;
牋牋 procedure Button1Click(Sender: TObject) ;
牋牋 procedure CallMeByName(Sender: TObject) ;
牋 private
牋牋 procedure ExecMethod(OnObject: TObject; MethodName: string) ;
牋 end;

var
牋 Form1: TForm1;

type
牋 TExec = procedure of object;

procedure TForm1.ExecMethod(OnObject: TObject; MethodName: string) ;
var
牋 Routine: TMethod;
牋 Exec: TExec;
begin
牋 Routine.Data := Pointer(OnObject) ;
牋 Routine.Code := OnObject.MethodAddress(MethodName) ;
牋 if NOT Assigned(Routine.Code) then Exit;
牋 Exec := TExec(Routine) ;
牋 Exec;
end;

procedure TForm1.CallMeByName(Sender: TObject) ;
begin
牋 ShowMessage('Hello Delphi!') ;
end;

procedure TForm1.Button1Click(Sender: TObject) ;
begin
牋 ExecMethod(Form1, 'CallMeByName') ;
end;

阅读全文
0 0

相关文章推荐

img
取 消
img