Is there a way to instantiate a class by its name in delphi?

后端 未结 2 2017
青春惊慌失措
青春惊慌失措 2020-12-01 17:01

I\'d like to instantiate a class but I only have its name in a string. Is there a way?

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 17:22

    This is from Delphi help (Delphi 2006, but also available from at least Delphi 7):

    Syntax function GetClass(const AClassName: string): TPersistentClass;

    Description Call GetClass to obtain a class from a class name. This class can be used as a parameter to routines that require a class. The Class must be registered before GetClass can find it. Form classes and component classes that are referenced in a form declaration (instance variables) are automatically registered when the form is loaded. Other classes can be registered by calling RegisterClass or RegisterClasses .

    Here some sample code. Works as such only because TButton is a TControl and therefore the typecast is valid.

    procedure TForm1.FormCreate(Sender: TObject);
    begin
      RegisterClasses([TButton, TForm]);
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var
      CRef : TPersistentClass;
      AControl : TControl;
    begin
      CRef := GetClass('TButton');
      if CRef<>nil then
      begin
         AControl := TControl(TControlClass(CRef).Create(Self));
         with AControl do
         begin
            Parent := Self;
            Width := 50;
            Height := 30;
         end;
      end;
    end;
    

提交回复
热议问题