如何在没有助手的情况下访问私有方法

如何在没有助手的情况下访问私有方法

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

问题描述

在 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

  • 字段 - privateprotectedpublicpublished
  • 方法 - public, published
  • 属性 - public, published
  • 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

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

08-15 14:06