delphi - 从类助手访问私有(private)字段

标签 delphi helper delphi-xe8

给定

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’。考虑到私有(private)成员的可见性受限,这正是我直觉所期望的 在声明类的单元之外,如果我没有看到 Marco Cantu 的 Delphi 2007 类助手手册的 p89/90 上的示例 它访问“帮助”类的私有(private)字段以及明确的声明 在这个问题的接受答案的开头段落中

Can I call static private class method with class helper?

这似乎支持它:“众所周知,助手确实会破坏私有(private)可见性。因此,私有(private)成员对于类助手是可见的。...”

那么,为什么我会收到 E2003 Undeclared Identifier 错误?在我的理解或代码中,我显然在某处遗漏了一些东西。我在使用 XE4 和 XE6 时遇到了同样的错误,顺便说一句,XE4 早于我引用的 SO 答案,这是去年的答案。

最佳答案

下面概述的解决方案适用于包括 Delphi Seattle 在内的版本。

出于我不知道的原因,您需要使用 Self 限定私有(private)实例成员。所以,这个编译:

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

与评论中的建议相反,方法也是如此。您需要显式包含 Self. 才能调用 helpee 中的私有(private)方法。

在 Delphi 10.1 Berlin 及更高版本中,不再可能访问助手中被助手的 strict privateprivate 成员。

关于delphi - 从类助手访问私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31972202/

相关文章:

multithreading - Delphi:WAITING线程完成

delphi - Delphi 程序终止时向用户显示消息

c - 将 C 指针代码示例转换为 Delphi 指针语法

android - 如何从 Delphi FireMonkey 连接到 SQL Server 数据库

sql - 数据库切换时出现错误 'Grid index out of range'

delphi - 64 位 delphi 应用程序中的 {$SetPEFlags IMAGE_FILE_LARGE_ADDRESS_AWARE}

laravel - 我正在使用 Laravel 5.2,是否有一些最佳建议将仅在 1 个 Controller 中使用的辅助函数放在哪里,

css - cakePHP 内联显示表单元素

ruby-on-rails - 助手中的 ActiveRecord