我如何在运行时最终使用RTTI将可视组件作为表单的子级创建?我所得到的只是一个TValue实例...
t := (ctx.FindType(Edit1.Text) as TRttiInstanceType);
inst:= t.GetMethod('Create').Invoke(t.MetaclassType,[Form1]);
谢谢!
纯粹的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] 删除。
我来说两句