如何在没有助手的情况下访问私人方法? [英] How to access private methods without helpers?

查看:151
本文介绍了如何在没有助手的情况下访问私人方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Delphi 10 Seattle中,我可以使用以下代码解决严格的可见性限制。

In Delphi 10 Seattle I could use the following code to work around overly strict visibility restrictions.

如何访问私有变量?

type 
  TBase = class(TObject)
  private
    FMemberVar: integer;
  end;

如何访问简单或虚拟的私有方法?

And how do I get access to plain or virtual private methods?

type
  TBase2 = class(TObject) 
  private
    procedure UsefullButHidden;  
    procedure VirtualHidden; virtual;
    procedure PreviouslyProtected; override;
  end;

以前我将使用类帮助来打开基类

type
  TBaseHelper = class helper for TBase
    function GetMemberVar: integer;

在Delphi 10.1 Berlin中,类帮助者不再可以访问主题类或记录的私人成员。

In Delphi 10.1 Berlin, class helpers no longer have access to private members of the subject class or record.

有没有其他方法来访问私人会员?

Is there an alternative way to access private members?

推荐答案

如果对类私有成员(字段和/或方法)生成了扩展的RTTI信息,可以使用它来访问它们。

If there is extended RTTI info generated for the class private members - fields and/or methods you can use it to gain access to them.

当然,通过RTTI访问

Of course, accessing through RTTI is way slower than it was through class helpers.

访问方法

var
  Base: TBase2;
  Method: TRttiMethod;

  Method := TRttiContext.Create.GetType(TBase2).GetMethod('UsefullButHidden');
  Method.Invoke(Base, []);

访问变量

var
  Base: TBase;
  v: TValue;

  v := TRttiContext.Create.GetType(TBase).GetField('FMemberVar').GetValue(Base);






为RTL / VCL / FMX生成的默认RTTI信息课程如下


Default RTTI information generated for RTL/VCL/FMX classes is following


  • 字段 - 私人 protected public 已发布

  • 方法 - code> public ,已发布

  • 属性 - public 已发布

  • Fields - private, protected, public, published
  • Methods - public, published
  • Properties - public, published

不幸的是,这意味着访问私有方法通过RTTI为核心Delphi库不可用。 @LU RD的答案涵盖了黑客,允许私人方法访问类,而不需要扩展RTTI。

Unfortunately, that means accessing private methods via RTTI for core Delphi libraries is not available. @LU RD's answer covers hack that allows private method access for classes without extended RTTI.

使用RTTI

这篇关于如何在没有助手的情况下访问私人方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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