从字符串在运行时创建Delphi Firemonkey组件

纳西斯·佩特鲁(Narcis Petru)

我如何在运行时最终使用RTTI将可视组件作为表单的子级创建?我所得到的只是一个TValue实例...

 t := (ctx.FindType(Edit1.Text) as TRttiInstanceType);
 inst:= t.GetMethod('Create').Invoke(t.MetaclassType,[Form1]);

谢谢!

雷米·勒博(Remy Lebeau)

纯粹的RTTI方法使用TRttiMethod.Invoke()如下所示:

var
  ctx: TRttiContext;
  t: TRttiInstanceType;
  m: TRttiMethod;
  params: TArray<TRttiParameter>;
  v: TValue;
  inst: TControl;
begin
  t := ctx.FindType(Edit1.Text) as TRttiInstanceType;
  if t = nil then Exit;
  if not t.MetaclassType.InheritsFrom(TControl) then Exit;
  for m in t.GetMethods('Create') do
  begin
    if not m.IsConstructor then Continue;
    params := m.GetParameters;
    if Length(params) <> 1 then Continue;
    if params[0].ParamType.Handle <> TypeInfo(TComponent) then Continue;
    v := m.Invoke(t.MetaclassType, [TComponent(Form1)]);
    inst := v.AsType<TControl>();
    // or: inst := TControl(v.AsObject);
    Break;
  end;
  inst.Parent := ...;
  ...
end;

一个不使用的简单得多的方法TRttiMethod.Invoke()如下所示:

type
  // TControlClass is defined in VCL, but not in FMX
  TControlClass = class of TControl;

var
  ctx: TRttiContext;
  t: TRttiInstanceType;
  inst: TControl;
begin
  t := ctx.FindType(Edit1.Text) as TRttiInstanceType;
  if t = nil then Exit;
  if not t.MetaclassType.InheritsFrom(TControl) then Exit;
  inst := TControlClass(t.MetaclassType).Create(Form4);
  inst.Parent := ...;
  //...
end;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Firemonkey组件在运行时移动

Delphi Firemonkey 在运行时创建 TExpanders 和 TLabels

Delphi / Firemonkey在运行时更改iOS屏幕旋转

选择在运行时创建的组件

在运行时角化,编译和创建组件

在运行时创建的组件中传播 viewModel

XamlParseException在运行时。从x:Static切换到相对组件字符串以引用图像可修复该问题。为什么?

Delphi 10.1 Firemonkey-检测鼠标在组件外部的单击

Delphi 10.1 Firemonkey-组件构造期间的属性值

FireMonkey使用RTTI在运行时获取FMXObjects

Delphi XE2在运行时不考虑组件属性

delphi调整屏幕大小后如何在运行时处理组件的重新对齐

更改 Firemonkey TMemo 组件中选定子字符串后面的背景颜色

如何在运行时创建的面板中创建组件?

如何在运行时在Firemonkey中创建和销毁TGrid-Android和iOS App Dev

如何在设计时编码仅在运行时创建的组件

angular2:如何在运行时创建的组件上使用EventEmitter?

Angular在运行时创建组件,需要向其添加数据

我可以在运行时通过评估字符串来创建函数吗?

在运行时在字符串中设置值

Dapper 在运行时更改连接字符串

尝试在运行时编辑字符串

在运行时验证MathText字符串

在运行时更改字符串

如何在运行时检查Vue组件的类型?

在运行时更改文本组件值

在运行时更改组件的ID名称

如何在运行时更新JSF组件的样式

在运行时反应本机动态注入组件