加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 如何访问私人方法没有帮助者?

发布时间:2020-12-15 10:18:27 所属栏目:大数据 来源:网络整理
导读:在Delphi 10 Seattle中,我可以使用以下代码解决过度严格的可见性限制。 如何访问私有变量? type TBase = class(TObject) private FMemberVar: integer; end; 而我如何获得普通或虚拟的私有方法? type TBase2 = class(TObject) private procedure UsefullB
在Delphi 10 Seattle中,我可以使用以下代码解决过度严格的可见性限制。

如何访问私有变量?

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

而我如何获得普通或虚拟的私有方法?

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

Previously I would use a class helper to break open the base class.

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

在Delphi 10.1 Berlin中,课堂助手不再能访问主题类或记录的私人成员。

有没有其他途径来访问私人会员?

解决方法

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

当然,通过RTTI的访问速度比通过课堂帮助者慢。

访问方式:

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信息如下

>字段 – 私人,受保护,公开,发布
>方法 – 公开发表
>属性 – 公开,已发布

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

Working with RTTI

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读