首先我们需要枚举接口的方法。不幸的是这个程序
{$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.
Run Code Online (Sandbox Code Playgroud)
不产生输出。
这个问题涵盖了这个问题:Delphi TRttiType.GetMethods return Zero TRttiMethodInstances。
如果您读到该问题的底部,答案表明编译{$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.
Run Code Online (Sandbox Code Playgroud)
输出是:
名称:Foo索引:3 名称: 酒吧指数: 4
请记住,所有接口均源自IInterface. 因此人们可能会期望其成员出现。然而,似乎IInterface是在状态下编译的{$M-}。这些方法似乎也是按顺序枚举的,尽管我没有理由相信这是保证的。
感谢 @RRUZ 指出VirtualIndex.