Delphi构造函数和类构造函数

时间:2016-09-13 13:54:03

标签: delphi

我怀疑我无法解决。我已经在embarcadero上阅读了class constructors的文档,但我无法理解其含义。换句话说,constructorclass 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时立即创建对象?

1 个答案:

答案 0 :(得分:20)

  • 类构造函数只在初始化声明它的单元时执行一次。类构造函数是静态类方法,因此未定义Self
  • 构造函数在显式调用时执行,并具有初始化类实例的工作。

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

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