从类帮助器访问私有字段 [英] Accessing private fields from a Class Helper

查看:73
本文介绍了从类帮助器访问私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定

type
  TMyClass = class
  private
    FPrivateInt : Integer;
  protected
    FProtectedInt : Integer;
  public
    FPublicInt : Integer;
  end;

一个单元和

type
  TMyHelper = class helper for TMyClass
    function Sum : Integer;
  end;
[...]
function TMyHelper.Sum: Integer;
begin
  Result := 0;
  Result := Result + FPublicInt;
  Result := Result + FProtectedInt;
  Result := Result + FPrivateInt;  // <- compiler error here
end;

在另一种情况下,XE8编译器报告错误 E2003未声明的标识符'FPrivateInt'。这就是我要的直观地预期,鉴于私人成员
在宣布班级的单位之外的可见度受到限制,如果我没有在Marco Cantu的Delphi 2007手册的第89/90页上看到班级帮助者
的示例它访问帮助类的私有字段,并且在该q的已接受答案的开头段落中明确声明

in another, the XE8 compiler reports error "E2003 undeclared identifier 'FPrivateInt'. This is what I would intuitively have expected, given the restricted visibility of private members outside the unit where a class is declared, if I hadn't seen the example on p89/90 of Marco Cantu's Delphi 2007 Handbook of a class helper which accesses private fields of the "helped" class and also an unequivocal statement in the opening paragraph of the accepted answer to this q

我可以使用类助手来调用静态私有类方法吗?

这似乎支持它:众所周知,助手确实可以提高个人知名度。因此,可以从班级助手中看到私人成员。 ...

which seems to support it: "As is widely known, helpers do crack private visibility. So, private members are visible from a class helper. ..."

那么,为什么我会收到E2003未声明的标识符错误?在我的理解或代码中,我显然缺少某些地方。 XE4和XE6,btw和XE4早于我引用的SO答案,该答案来自去年。

So, why do I get the E2003 Undeclared Identifier error? I am obviously missing something somewhere, in my understanding or code. I get the same error using XE4 and XE6, btw, and XE4 pre-dates the SO answer I've referenced, which is from last year.

推荐答案

下面概述的解决方案适用于Delphi Seattle以及更高版本。

The solution outlined below works for versions up to and including Delphi Seattle.

由于我不知道的原因,您需要使用 Self限定私有实例成员。因此,它将编译为:

For reasons unknown to me, you need to qualify private instance members with Self. So, this compiles:

function TMyHelper.Sum: Integer;
begin
  Result := 0;
  Result := Result + FPublicInt;
  Result := Result + FProtectedInt;
  Result := Result + Self.FPrivateInt;
end;

与注释中的建议相反,方法也是如此,您需要明确包含 Self。在被帮助者中调用私有方法。

Contrary to the suggestions in the comments, the same is true for methods. You would need to explicitly include Self. to call a private method in the helpee.

在Delphi 10.1 Berli中n及更高版本,将不再可能在帮助器中访问受援者的严格私有 private 成员。

In Delphi 10.1 Berlin and beyond it is no longer possible to access strict private or private members of the helpee in a helper.

这篇关于从类帮助器访问私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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