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

后端 未结 10 1356
旧时难觅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:32

    You didn't specify your Delphi version, However if you have Delphi 2010(+) you can do it using the enhanced RTTI, I'm not expert on them, but I tried this sample for you:

      TProcClass = class
        public
          procedure SayHi;
          function GetSum(X,Y:Integer): Integer;
      end;
    
    uses
      Rtti;
    
    { TProcClass }
    
    procedure TProcClass.SayHi;
    begin
      ShowMessage('Hi');
    end;
    
    function TProcClass.GetSum(X, Y: Integer): Integer;
    begin
      ShowMessage(IntToStr(X + Y));
    end;
    
    procedure ExecMethod(MethodName:string; const Args: array of TValue);
    var
     R : TRttiContext;
     T : TRttiType;
     M : TRttiMethod;
    begin
      T := R.GetType(TProcClass);
      for M in t.GetMethods do
        if (m.Parent = t) and (m.Name = MethodName)then
          M.Invoke(TProcClass.Create,Args)
    end;
    
    procedure TForm1.FormCreate(Sender: TObject);
    begin
      ExecMethod('SayHi',[]);
      ExecMethod('GetSum',[10,20]);
    end;
    

    The good things, if you have procedure or function with parameters it will work without more work.

提交回复
热议问题