为什么我可以从 class 外部访问私有 class 变量,我该如何防止它?

Why am I able to access private class variables from outside the class, and how can I prevent it?

我正在使用此代码

type
 TSomeClass = class(TOBject)
 private
  class var InstanceCount : integer;
  class var TotalInstanceCount : integer;
 public
  class function instances: integer;
  class function totalInstances: integer;
  constructor Create;
  destructor Destroy;
end;

constructor TSomeClass.Create;
begin
 inherited Create;
 Inc(InstanceCount);
 Inc(TotalInstanceCount);
end;

destructor TSomeClass.Destroy;
begin
 Dec(InstanceCount);
 inherited;
end;

class function TSomeClass.instances;
begin
  Result := InstanceCount;
end;

class function TSomeClass.totalInstances;
begin
  Result := TotalInstanceCount;
end;

我想创建一个实例计数器,并将一些 class 变量设置为私有。问题很简单,看这张图:

正如您在红色框中看到的,有 class 个变量是我声明为私有的。我不想让他们出现。我只希望 public class 函数能够显示计数器。我能做什么?

documentation 中所述,可以从定义 class 的单元内的任何位置访问 class 的 private 部分。为了避免这种情况,并避免从同一单元的其他地方访问这些私有 class 成员,请改用 strict private

当然,如果您的应用程序的设计需要它,您也可以将此 class 移动到另一个单元,这反过来也会产生您正在寻找的效果。