我怀疑我无法解决。我已经在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
时立即创建对象?
答案 0 :(得分:20)
Self
。在野外,类构造函数很少,构造函数与muck一样普遍。很可能你没有立即需要类构造函数,所以现在可以随意忽略它们。专注于理解如何编写和使用构造函数。
如果将来你需要初始化类拥有的变量(而不是实例拥有的变量),那么你可能会发现自己想要使用类构造函数。在那个时间点之前,请随意忽略它们。