delphi - 如何查找接口(interface)中方法的索引?

标签 delphi delphi-xe7

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

最佳答案

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

{$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.

输出为:

Name: FooIndex: 3
Name: BarIndex: 4

请记住,所有接口(interface)均派生自 IInterface。因此人们可能会期望其成员出现。然而,IInterface似乎是在{$M-}状态下编译的。这些方法似乎也是按顺序枚举的,尽管我没有理由相信这是保证的。

感谢@RRUZ指出VirtualIndex的存在。

关于delphi - 如何查找接口(interface)中方法的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27969212/

相关文章:

delphi - 是否可以在虚拟 TreeView 中选择多个列?

delphi - 为什么 Delphi 2009 不为太长的字符串常量提供消息?

c - Delphi 中通过引用传递的指针(从 DLL 导入函数)

delphi - 从大 GIF 中检索第一帧(在最佳时间内)

delphi - TChangeTabAction FMX XE7 - Embarcadero 的想法是什么?

delphi - 在64位Delphi程序中CreateOleObject?

android - 在Delphi XE7 Android中的Messagedlg

delphi - 以公制单位准确计算文本宽度

delphi - 如何在 Delphi 中触发从 Web 服务器到客户端的事件?

XMLDocument 节点没有值