【发布时间】: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