我应该在从TObject或TPersistent派生的类的构造函数中调用"inherited“吗?
constructor TMyObject.Create;
begin
inherited Create; // Delphi doc: Do not create instances of TPersistent. Use TPersistent as a base class when declaring objects that are not components, but that need to be saved to a stream or have their properties assigned to other objects.
VectorNames := TStringList.Create;
Clear;
end;发布于 2009-04-21 12:37:31
是。它什么也做不了,没错,但它是无害的。我认为,始终一致地调用继承的构造函数是有价值的,而不是检查是否确实有实现。有些人会说,调用继承的Create是值得的,因为Embarcadero将来可能会为TObject.Create添加一个实现,但我怀疑这是真的;它会破坏不调用继承创建的现有代码。尽管如此,我认为仅仅为了一致性的原因而调用它是一个好主意。
发布于 2009-04-21 12:46:01
我总是这么做。
如果您正在重构代码并将代码移动到公共祖先,则调用继承的Create具有以下优点:
发布于 2009-04-21 13:34:22
你也可以重写"procedure AfterConstruction“。无论是哪种构造函数,此过程都会被调用。
public
procedure AfterConstruction; override;
end;
procedure TfrmListBase.AfterConstruction;
begin
inherited;
//your stuff, always initialized, no matter what kind of constructor!
end;例如:如果您想创建一个具有不同于普通TObject.Create的构造函数的对象,例如TComponent.Create(AOwner)或自定义(重载)构造函数,您可能会遇到问题,因为您的重写没有被调用,并且(在本例中)您的"VectorNames“变量将为空。
https://stackoverflow.com/questions/772336
复制相似问题