访问Delphi类的严格保护属性

访问Delphi类的严格保护属性

本文介绍了访问Delphi类的严格保护属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要访问严格受保护的属性,因为我需要创建验证(基于此属性的值)以避免错误。 (我没有具有此属性的第三方类的源代码)只有我有类(接口)和dcu(所以我不能更改属性可见性)的定义。问题是存在一种访问严格保护财产的方法? (我真的读了,但是我没有找到关于这个特定主题的内容。)

I need to access a strict protected property, because I need to create a validation (based in the value of this property) to avoid a bug. (I don't have the source code of the third party class which has this property) only I have the definition of the class (interface) and the dcu (so I can't change the property visibility). The question is Exist a way to access a strict protected property? (I really read the Hallvard Vassbotn Blog, but I don't find anthing about this particular topic.)

推荐答案

这个类助手示例编译好:

This class helper example compiles fine :

type
  TMyOrgClass = class
  strict private
    FMyPrivateProp: Integer;
  strict protected
    property MyProtectedProp: Integer read FMyPrivateProp;
  end;

  TMyClassHelper = class helper for TMyOrgClass
  private
    function GetMyProtectedProp: Integer;
  public
    property MyPublicProp: Integer read GetMyProtectedProp;
  end;

function TMyClassHelper.GetMyProtectedProp: Integer;
begin
  Result:= Self.FMyPrivateProp;  // Access the org class with Self
end;

有关类帮助器的更多信息可以在这里找到:应用程序 - 帮助程序 - 开发中的新代码

Some more information about class helpers can be found here : should-class-helpers-be-used-in-developing-new-code

更新

从Delphi 10.1柏林开始,访问 private strict private 成员与类帮助者不工作。它被认为是一个编译器错误,并已被更正。 保护或严格保护成员仍然可以通过类助手进行。

Starting with Delphi 10.1 Berlin, accessing private or strict private members with class helpers does not work. It was considered a compiler bug and has been corrected. Accessing protected or strict protected members is still allowed with class helpers though.

在上面的例子中,说明了对私有成员的访问。下面显示了访问严格保护成员的工作示例。

In the above example access to a private member was illustrated. Below shows a working example with access to a strict protected member.

function TMyClassHelper.GetMyProtectedProp: Integer;
begin
  Result:= Self.MyProtectedProp;  // Access strict protected property
end;

这篇关于访问Delphi类的严格保护属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!