How do I instantiate a class from its TRttiType?

前端 未结 2 545
逝去的感伤
逝去的感伤 2021-02-09 01:44

I want to create a form given its class name as a string, which has been asked about before, but instead of calling GetClass, I want to use Delphi\'s new RTTI featu

2条回答
  •  走了就别回头了
    2021-02-09 02:38

    You should use the TRttiContext.FindType() method instead of manually looping through though the TRttiContext.GetTypes() list, eg:

    lType := ctx.FindType('ScopeName.UnitName.TFormFormulirPendaftaran');
    if lType <> nil then
    begin
      ...
    end;
    

    But either way, once you have located the TRttiType for the desired class type, you can instantiate it like this:

    type
      TFormBaseClass = class of TFormBase;
    
    f := TFormBaseClass(GetTypeData(lType.Handle)^.ClassType).Create(TheDesiredOwnerHere);
    

    Or this, if TFormBase is derived from TForm:

    f := TFormClass(GetTypeData(lType.Handle)^.ClassType).Create(TheDesiredOwnerHere);
    

    Or this, if TFormBase is derived from TCustomForm:

    f := TCustomFormClass(GetTypeData(lType.Handle)^.ClassType).Create(TheDesiredOwnerHere);
    

    Update: Or, do it like @RRUZ showed. That is more TRttiType-oriented, and doesn't rely on using functions from the older TypInfo unit.

提交回复
热议问题