尝试调用功能tru RTTI;无效的类型转换

问题描述 投票:1回答:1

我正在尝试在运行时从类(对象)调用函数。

找到对象,找到方法,并将参数存储在TValue数组中。

[调用TRttiMetho.Invoke时,触发以下错误

无效的类型转换

怎么了?

    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);
delphi rtti delphi-10.2-tokyo
1个回答
2
投票

您正在使用错误的第一个参数调用Invoke。如果该方法是常规方法,则需要传递调用该​​方法的对象的实例。如果它是一个类方法,则需要传递该方法的TClass

documentation甚至解释了它。

您什么都不做,只传递了vitype,它是TRttiInstanceType类型的实例。

© www.soinside.com 2019 - 2024. All rights reserved.