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柏林开始,访问private或strict private使用类助手的成员不起作用.它被认为是一个编译器错误,并已得到纠正.但是仍然允许访问protected或strict protected成员与课程助手.
在上面的示例中,说明了对私有成员的访问.下面显示了一个可以访问严格受保护成员的工作示例.
function TMyClassHelper.GetMyProtectedProp: Integer;
begin
with Self do Result:= MyProtectedProp; // Access strict protected property
end;
Run Code Online (Sandbox Code Playgroud)
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类上实际实现一个方法,使其公开,并将该方法用作到目标严格保护成员的路由.
| 归档时间: |
|
| 查看次数: |
4217 次 |
| 最近记录: |