如何从TRttiType实例化一个类?

Niy*_*wan 8 delphi rtti delphi-xe2

我想创建一个表单,将其类名称作为字符串,之前已经被问过,但是GetClass我想使用Delphi的新RTTI功能而不是调用.

有了这段代码,我有一个TRttiType,但我不知道如何实例化它.

var
  f:TFormBase;
  ctx:TRttiContext;
  lType:TRttiType;
begin
  ctx := TRttiContext.Create;
  for lType in ctx.GetTypes do
  begin
    if lType.Name = 'TFormFormulirPendaftaran' then
    begin
      //how to instantiate lType here?
      Break;
    end;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

我也试过lType.NewInstance没有运气.

RRU*_*RUZ 11

您必须将类型TRttiType转换为TRttiInstanceType类,然后使用该GetMethod函数调用构造函数.

试试这个样本

var
  ctx:TRttiContext;
  lType:TRttiType;
  t : TRttiInstanceType;
  f : TValue;
begin
  ctx := TRttiContext.Create;
  lType:= ctx.FindType('UnitName.TFormFormulirPendaftaran');
  if lType<>nil then
  begin
    t:=lType.AsInstance;
    f:= t.GetMethod('Create').Invoke(t.MetaclassType,[nil]);
    t.GetMethod('Show').Invoke(f,[]);
  end;
end;
Run Code Online (Sandbox Code Playgroud)