给定
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 private
或 private
成员。
关于delphi - 从类助手访问私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31972202/