我正在尝试在运行时从类(对象)调用函数。
找到对象,找到方法,并将参数存储在 TValue 数组中。
调用TRttiMetho.Invoke
时,触发以下错误
Invalid Typecast
出了什么问题?
…
vcontext: TRTTIContext;
vtype: TRttiType;
vitype: TRttiInstanceType;
vmethod: TRttiMethod;
vparams: TArray<TRttiParameter>;
vparam: array of TValue;
begin
vcontext := TRttiContext.Create;
for vtype in vcontext.GetTypes do
begin
if (vtype.QualifiedName = 'somemodule.sometype') then // this is found
begin
if vtype.IsInstance then
begin
vitype := (vtype as TRttiInstanceType);
for vmethod in vitype.GetMethods do
begin
if (vmethod.Name = 'Somefunction') then // this is found
begin
vparams := vmethod.GetParameters; // actually I know tha there are 2 Parameters
SetLength(vparam, Length(vparams));
vparam[0] := TValue.From(Ord(SomeEnum));
vparam[1] := TValue.From<TSomeObject>(Object);
vmethod.Invoke(vitype, vparam); // Invalid Typecast here in
end;
end;
end;
end;
end;
vcontext.Free;
end;
…
错误出现在 TRttiInstanceMethodEx.DispatchInvoke
第 5853 行:
if (cls <> nil) and not cls.InheritsFrom(TRttiInstanceType(Parent).MetaclassType) then
raise EInvalidCast.CreateRes(@SInvalidCast);
最佳答案
您使用错误的第一个参数调用 Invoke。如果该方法是常规方法,则需要传递调用该方法的对象的实例。如果是类方法,则需要传递该方法的TClass
。
documentation甚至解释了它。
您没有执行任何操作,而是传递 vitype
,它是 TRttiInstanceType
类型的实例。
关于delphi - 尝试调用 tru RTTI 函数;无效的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59252845/