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

Sal*_*dor 16 delphi class-helpers delphi-xe

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

LU *_* RD 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;
Run Code Online (Sandbox Code Playgroud)

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

更新

从Delphi 10.1柏林开始,访问privatestrict private使用类助手的成员不起作用.它被认为是一个编译器错误,并已得到纠正.但是仍然允许访问protectedstrict protected成员与课程助手.

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

function TMyClassHelper.GetMyProtectedProp: Integer;
begin
  with Self do Result:= MyProtectedProp;  // Access strict protected property
end;
Run Code Online (Sandbox Code Playgroud)

  • @alitrun,如果您研究了对我的答案所做的更新,您会发现仍然可以使用类助手访问受保护的方法.此外,还有另一个技巧可以打开柏林/东京的私人/受保护领域.只需在帮助器中写下这个:`with Self do begin {any field/method is here here}};` (2认同)

Dav*_*nan 15

您可以使用标准protectedhack 的变体.

单元1

type
  TTest = class
  strict private
    FProp: Integer;
  strict protected
    property Prop: Integer read FProp;
  end;
Run Code Online (Sandbox Code Playgroud)

单元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;
Run Code Online (Sandbox Code Playgroud)

第3单元

var
  T: TTest;

....

THackedTest(T).Prop;
Run Code Online (Sandbox Code Playgroud)

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

  • @WarrenP:这个解决方案非常安全,因为继承的类共享原始类的内存布局.THackedTest不添加任何变量或虚拟方法. (2认同)