一个更简洁的根据函数名执行函数的例子!

By | 2020年5月16日

比前面发的更简洁! 不需要定义类, 一个函数搞定!

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
   TForm1 = class(TForm)
     Button1: TButton;
     procedure Button1Click(Sender: TObject) ;
     procedure MyFunc(AText: String) ;
   private
   end;

var
  Form1: TForm1;

procedure ExecMethod(OnObject: TObject; MethodName: string;AMsg:String) ;

implementation

{$R *.dfm}


procedure ExecMethod(OnObject: TObject; MethodName: string;AMsg:String) ;
type
     TExec = procedure(AText:String) of object;
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(AMsg);
end;

procedure TForm1.MyFunc(AText: String) ;
begin
   ShowMessage(AText) ;
end;

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

end.

发表评论

电子邮件地址不会被公开。 必填项已用*标注