【问题标题】:Delphi constructor and class constructorDelphi构造函数和类构造函数
【发布时间】:2017-01-21 03:55:14
【问题描述】:

我有一个无法解决的疑问。我已经在 embarcadero 阅读了class constructors 的文档,但我无法理解它的含义。换句话说,constructor 和class constructor 之间的使用区别是什么?我这样做了:

type
 TGeneric<T> = class
  private
   FValue: T;
   aboutString: string;
   procedure setValue(const a: T);
  public
   property V: T read FValue write setValue;
   property about: string read aboutString;
   constructor Create;
   destructor Destroy; override;
 end;

implementation

{ TGeneric<T> }

constructor TGeneric<T>.Create;
begin
  inherited;
  aboutString := 'test';
end;

相反,这段代码不能正常工作:

type
 TGeneric<T> = class
  private
   FValue: T;
   aboutString: string;
   procedure setValue(const a: T);
  public
   property V: T read FValue write setValue;
   property about: string read aboutString;
   class constructor Create;
   destructor Destroy; override;
 end;

implementation

{ TGeneric<T> }

class constructor TGeneric<T>.Create;
begin
  inherited;
  aboutString := 'test';
end;

我猜答案在文档的这一行:

通常,类构造函数用于初始化静态字段 的类或执行一种类型的初始化,这是必需的 在类或任何类实例可以正常运行之前。

告诉我我是否正确:

  • 构造函数:我可以使用inherited Create;,初始化变量等等。
  • 类构造函数:当我必须立即在我的类中创建一个对象时,我可以使用它吗?

例如看下面:

type
   TBox = class
   private
     class var FList: TList<Integer>;
     class constructor Create;
   end;

 implementation

 class constructor TBox.Create;
 begin
   { Initialize the static FList member }
   FList := TList<Integer>.Create();
 end;

 end.

这里我要在主窗体中调用TBox.Create时立即创建对象?

【问题讨论】:

  • 将类构造函数视为自动启动类类型的一种方式。它们在启动时会自动调用,您永远不应该通过代码调用它们。换句话说,类构造函数对类型进行操作,而普通构造函数对变量进行操作。
  • 所以我可以避免这种情况,只关心经典的构造函数?
  • 这取决于你想做什么。类 var 是该类型的一种全局变量,在某些情况下很有用。

标签: delphi


【解决方案1】:
  • 当声明它的单元初始化时,类构造函数只执行一次。类构造函数是静态类方法,因此没有定义Self。
  • 构造函数在显式调用时执行,并负责初始化类的实例。

在野外,类构造函数很少见,构造函数和垃圾一样常见。很可能您没有立即需要类构造函数,所以现在可以随意忽略它们。专注于理解如何编写和使用构造函数。

如果将来您需要初始化类拥有的变量(而不是实例拥有的变量),那么您可能会发现自己想要使用类构造函数。在此之前,请随意忽略它们。

【讨论】:

  • 请注意,class constructor only 仅在使用该类时执行。因此,与单元的普通initialization 部分(始终执行)不同,它仅在类被使用somewhere 时执行。 class destructor 也是如此。
  • 当且仅当引用该单元时,才会执行初始化部分。同样是类构造函数。仅在类被引用时调用。
  • 仅当类被使用时。您可以声明该类的变量,但它不会运行。一旦包含单元,初始化部分总是运行。
  • @RudyVelthuis 是的。我发现很难弄清楚“使用类”的实际含义。例如,这足以让类的类构造函数在 XE7 的 Win32 编译器上运行:var obj: TMyClass; begin obj := nil; end.
  • @David 在 Delphi 10.2 中,类构造函数根本没有“Self”(与其他类方法不同)。编译器报告“未声明的标识符”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 1970-01-01
  • 2021-08-14
  • 2011-04-22
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多