delphi – 如何使用类的地址和变量的偏移量来访问类var的值?
发布时间:2020-12-15 09:36:15 所属栏目:大数据 来源:网络整理
导读:我需要使用他的实例和变量的偏移来访问类的严格私有类var值. 到目前为止尝试了这个,检查这个示例类 type TFoo=class strict private class var Foo: Integer; public constructor Create; end;constructor TFoo.Create;begin inherited; Foo:=666;end;//this
我需要使用他的实例和变量的偏移来访问类的严格私有类var值.
到目前为止尝试了这个,检查这个示例类 type TFoo=class strict private class var Foo: Integer; public constructor Create; end; constructor TFoo.Create; begin inherited; Foo:=666; end; //this function works only if I declare the foo var as //strict private var Foo: Integer; function GetFooValue(const AClass: TFoo): Integer; begin Result := PInteger(PByte(AClass) + 4)^ end; 如您所见,函数GetFooValue仅在foo变量未声明为类var时才起作用. 问题是我必须如何修改GetFooValue以获得Foo的值,当声明为严格私有类var Foo:Integer时; 解决方法
要访问严格的私有类var,要使用Class Helper进行救援.
示例: type TFoo = class strict private class var Foo : Integer; end; TFooHelper = class helper for TFoo private function GetFooValue : Integer; public property FooValue : Integer read GetFooValue; end; function TFooHelper.GetFooValue : Integer; begin Result:= Self.Foo; // Access the org class with Self end; function GetFooValue( F : TFoo) : Integer; begin Result:= F.GetFooValue; end; Var f : TFoo;//don't need to instantiate since we only access class methods begin WriteLn(GetFooValue(f)); ReadLn; end. 更新了适合问题的示例. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |