如何找到接口中定义的过程/函数的索引?可以用RTTI来实现吗?
首先我们需要枚举接口的方法。不幸的是这个程序
{$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 实例 https://stackoverflow.com/questions/3004045/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
请记住,所有接口都源自IInterface
。因此人们可能会期望其成员出现。然而,似乎IInterface
被编译在{$M-}
状态。这些方法似乎也是按顺序枚举的,尽管我没有理由相信这是保证的。
感谢@RRUZ 指出存在VirtualIndex http://docwiki.embarcadero.com/Libraries/en/System.Rtti.TRttiMethod.VirtualIndex.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)