【问题标题】:How to find index of a method in an interface?如何在接口中查找方法的索引?
【发布时间】:2015-01-15 17:19:46
【问题描述】:

如何找到接口中定义的过程/函数的索引?可以用 RTTI 完成吗?

【问题讨论】:

    标签: delphi delphi-xe7


    【解决方案1】:

    首先我们需要枚举接口的方法。不幸的是这个程序

    {$APPTYPE CONSOLE}
    
    uses
      System.SysUtils, System.Rtti;
    
    type
      IMyIntf = interface
        procedure Foo;
      end;
    
    procedure EnumerateMethods(IntfType: TRttiInterfaceType);
    var
      Method: TRttiMethod;
    begin
      for Method in IntfType.GetDeclaredMethodsdo
        Writeln('Name: ' + Method.Name + 'Index: ' + IntToStr(Method.VirtualIndex));
    end;
    
    var
      ctx: TRttiContext;
    
    begin
      EnumerateMethods(ctx.GetType(TypeInfo(IMyIntf)) as TRttiInterfaceType);
    end.
    

    不产生任何输出。

    这个问题涵盖了这个问题:Delphi TRttiType.GetMethods return zero TRttiMethod instances

    如果您仔细阅读该问题的底部,则答案表明使用 {$M+} 编译将导致发出足够的 RTTI。

    {$APPTYPE CONSOLE}
    
    {$M+}
    
    uses
      System.SysUtils, System.Rtti;
    
    type
      IMyIntf = interface
        procedure Foo(x: Integer);
        procedure Bar(x: Integer);
      end;
    
    procedure EnumerateMethods(IntfType: TRttiInterfaceType);
    var
      Method: TRttiMethod;
    begin
      for Method in IntfType.GetDeclaredMethods do
        Writeln('Name: ' + Method.Name + 'Index: ' + IntToStr(Method.VirtualIndex));
    end;
    
    var
      ctx: TRttiContext;
    
    begin
      EnumerateMethods(ctx.GetType(TypeInfo(IMyIntf)) as TRttiInterfaceType);
    end.
    

    输出是:

    名称:FooIndex:3 名称: BarIndex: 4

    请记住,所有接口都派生自 IInterface。所以人们可能会期望它的成员出现。但是,IInterface 似乎是在{$M-} 状态下编译的。似乎这些方法也是按顺序列举的,尽管我没有理由相信这是有保证的。

    感谢@RRUZ 指出VirtualIndex 的存在。

    【讨论】:

    • 让我想知道如何列出继承/覆盖的。
    • @JerryDodge 我们在谈论接口
    • 是的,我知道这一点。接口可以被继承(而是重新声明的方法)
    • @DavidHeffernan,您可以使用VirtualIndex 属性来获取方法的索引,如Writeln(Format('Name: %s Index %d', [Method.Name, Method.VirtualIndex]));
    • @John 只需将该代码添加到我的答案中的代码中即可。我会尽快更新。
    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多