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

时间:2011-11-30 17:09:14

标签: delphi delphi-xe class-helpers

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:15)

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

第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;

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

相关问题