访问Delphi类的严格受保护属性?

问题描述 投票:16回答:2

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

delphi delphi-xe class-helpers
2个回答
23
投票

这个类助手示例编译正常:

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

更新

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

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

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

15
投票

您可以使用标准protected hack的变体。

单元1

type
  TTest = class
  strict private
    FProp: Integer;
  strict protected
    property Prop: Integer read FProp;
  end;

单元2

type
  THackedTest = class(TTest)
  strict private
    function GetProp: Integer;
  public
    property Prop: Integer read GetProp;
  end;

function THackedTest.GetProp: Integer;
begin
  Result := inherited Prop;
end;

第3单元

var
  T: TTest;

....

THackedTest(T).Prop;

严格保护仅允许您从定义类和子类访问成员。因此,您必须在crack类上实际实现一个方法,使其公开,并将该方法用作到目标严格保护成员的路由。

© www.soinside.com 2019 - 2024. All rights reserved.