Delphi: Call a function whose name is stored in a string

后端 未结 10 1345
旧时难觅i
旧时难觅i 2020-12-08 05:30

Is it possible to call a function whose name is stored in a string in Delphi?

10条回答
  •  天命终不由人
    2020-12-08 05:50

    OK, I'm very late to the party, but you can definitely call routines by name with this code (There are some limitations thought)

    type
        TExec = procedure of Object;
        // rest of section...
    
    procedure TMainForm.ExecuteMethod(MethodName : String);
    var
       Exec    : TExec;
       Routine : TMethod;
    begin
         Routine.Data := Pointer(Form1);
         Routine.Code := Form1.MethodAddress(MethodName);
         if Not Assigned(Routine.Code) then
            Exit;
    
         Exec         := TExec(Routine);
         Exec;
    end;
    

    Just in case someone needs this for Delphi 7 / 2010

提交回复
热议问题