微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

delphi – 如何从TRttiType实例化一个类?

我想创建一个表格,它的类名称为字符串,which has been asked about before,但我不想调用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;

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

解决方法

必须将 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;

原文地址:https://www.jb51.cc/delphi/102315.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐