delphi – 如何在接口中查找方法的索引?
发布时间:2020-12-15 09:15:30 所属栏目:大数据 来源:网络整理
导读:如何找到Interface中定义的过程/函数索引?可以用RTTI完成吗? 解决方法 首先,我们需要枚举接口的方法.不幸的是这个程序 {$APPTYPE CONSOLE}uses System.SysUtils,System.Rtti;type IMyIntf = interface procedure Foo; end;procedure EnumerateMethods(Intf
如何找到Interface中定义的过程/函数索引?可以用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 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指出 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |