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

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

    I'm surprised no one has suggested a dispatch table. This is exactly what it's for.

    program RPS;
    
    uses
      SysUtils,
      Generics.Collections;
    
    type
      TDispatchTable = class(TDictionary);
    
    procedure Rock;
    begin
    end;
    
    procedure Paper;
    begin
    end;
    
    procedure Scissors;
    begin
    end;
    
    var
      DispatchTable: TDispatchTable;
    
    begin
      DispatchTable := TDispatchTable.Create;
      try
        DispatchTable.Add('Rock', Rock);
        DispatchTable.Add('Paper', Paper);
        DispatchTable.Add('Scissors', Scissors);
    
        DispatchTable['Rock'].Invoke; // or DispatchTable['Rock']();
      finally
        DispatchTable.Free;
      end;
    end.
    

    The implementation I wrote uses generics so it would only work with Delphi 2009+. For older versions it would probably be easiest to implement using TStringList and the command pattern

提交回复
热议问题