德尔福:在后裔班给私人祖先的领域写信 [英] Delphi: writing to the private ancestor's field in descendant class

查看:177
本文介绍了德尔福:在后裔班给私人祖先的领域写信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要修复第三方组件。这个组件的类有其后代主动使用的私有变量:

  TThirdPartyComponentBase = class 
private
FSomeVar:整数
public
...
end;

TThirdPartyComponent = class(TThirdPartyComponentBase)
protected
procedure Foo;虚拟;
结束

程序TThirdPartyComponent.Foo;
begin
FSomeVar:= 1; //访问私人领域!
结束

这是因为这两个类都在同一个单元中,所以他们有点朋友 / p>

但是,如果我尝试在新单位中创建一个新课程

  TMyFixedComponent = class(TThirdPartyComponent)
procedure Foo;覆盖
结束

我无法访问FSomeVar,但是我需要使用它来修复。而我真的不想在我的代码中复制所有这些基础树。



如果有可能,您可以建议一些快速入侵访问该私人领域而不更改原始组件的单位

解决方案

您必须使用hack才能访问不同单位中任何类(包括基类)的私有字段。在您的单位中定义的情况:

 键入
__TThirdPartyComponentBase = class
private
FSomeVar : 整数;
结束

然后获取访问权限:

  __ TThirdPartyComponentBase(Self).FSomeVar:= 123; 

当然这是危险的,因为您需要控制基类中的更改。因为如果字段布局会改变,你会错过这个事实,那么上述方法会导致故障,AV等。


I need to fix a third-party component. This component's class has private variable which is actively used by its descendants:

TThirdPartyComponentBase = class
private
  FSomeVar: Integer;
public
  ...
end;

TThirdPartyComponent = class (TThirdPartyComponentBase)
protected
   procedure Foo; virtual;
end;

procedure TThirdPartyComponent.Foo;
begin
  FSomeVar := 1; // ACCESSING PRIVATE FIELD!
end; 

This works because both classes are in the same unit, so they're kinda "friends".

But if I'll try to create a new class in a new unit

TMyFixedComponent = class (TThirdPartyComponent)
  procedure Foo; override; 
end;

I can't access FSomeVar anymore, but I need to use it for my fix. And I really don't want to reproduce in my code all that tree of base classes.

Can you advise some quick hack to access that private field without changing the original component's unit if it's possible at all?

解决方案

You have to use a hack to access a private field in any class (including a base class) in a different unit. In your case define in your unit:

type
  __TThirdPartyComponentBase = class 
  private 
    FSomeVar: Integer;
  end;

Then get the access:

__TThirdPartyComponentBase(Self).FSomeVar := 123;

Of course, that is dangerous, because you will need to control changes in the base class. Because if the fields layout will be changed and you will miss this fact, then the above approach will lead to failures, AV's, etc.

这篇关于德尔福:在后裔班给私人祖先的领域写信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆