如何找到接口(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/