如何在接口中找到方法的索引? [英] How to find index of a method in an interface?

查看:80
本文介绍了如何在接口中找到方法的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何找到接口中定义的过程/功能的索引?

How can I find index of procedure/function which is defined in Interface? Can it be done with RTTI?

推荐答案

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

First of all we need to enumerate the methods of the interface. Unfortunately this program

{$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返回零个TRttiMethod实例

This question covers this issue: Delphi TRttiType.GetMethods return zero TRttiMethod instances.

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

If you read down to the bottom of that question an answer states that compiling with {$M+} will lead to sufficient RTTI being emitted.

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

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

Remember that all interfaces derive from IInterface. So one might expect its members to appear. However, it seems that IInterface is compiled in {$M-} state. It also seems that the methods are enumerated in order, although I've no reason to believe that is guaranteed.

感谢@RRUZ指出 VirtualIndex

Thanks to @RRUZ for pointing out the existence of VirtualIndex.

这篇关于如何在接口中找到方法的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆