访问 Delphi 类的严格保护的属性? [英] Access a strict protected property of a Delphi class?

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

问题描述

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

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;

可以在此处找到有关类助手的更多信息:should-class-helpers-be-used-in-developing-new-code

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

更新

从 Delphi 10.1 Berlin 开始,使用类助手访问 privatestrict private 成员不起作用.它被认为是一个编译器错误并已得到纠正.尽管如此,类助手仍然允许访问 protectedstrict protected 成员.

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
  with Self do Result:= MyProtectedProp;  // Access strict protected property
end;

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

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