如何使用最终RTTI在运行时创建可视组件作为表单的子项? 我得到的只是一个TValue实例......
t := (ctx.FindType(Edit1.Text) as TRttiInstanceType);
inst:= t.GetMethod('Create').Invoke(t.MetaclassType,[Form1]);
谢谢!
答案 0 :(得分:1)
使用TRttiMethod.Invoke()
的纯粹RTTI方法看起来像这样:
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;