如何从其TRttiType实例化一个类? [英] How do I instantiate a class from its TRttiType?

查看:60
本文介绍了如何从其TRttiType实例化一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个以其类名作为字符串的表单,

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 feature.

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

With this code, I've got a TRttiType, but I don't know how to instantiate it.

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;

我也尝试过 lType.NewInstance ,但是没有运气.

I've also tried lType.NewInstance with no luck.

推荐答案

您必须转换 TRttiType TRttiInstanceType 类,然后使用 GetMethod 函数.

You must cast the TRttiType to the TRttiInstanceType class and then invoke the constructor using the GetMethod function.

尝试此示例

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;

这篇关于如何从其TRttiType实例化一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆