使用继承于“创建”一个TObject的构造函数 [英] Using inherited in the "Create" constructor of an TObject

查看:185
本文介绍了使用继承于“创建”一个TObject的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该在派生自TObject或TPersistent的类的构造函数中调用inherited?

 构造函数TMyObject.Create; 
开始
继承创建; // Delphi doc:不要创建TPersistent的实例。当声明不是组件的对象,但需要保存到流或将其属性分配给其他对象时,使用TPersistent作为基类。
VectorNames:= TStringList.Create;
清除;
结束


解决方案

是的。它什么也没有,但它是无害的。我认为总是调用继承的构造函数是一致的,而不检查实际上是否存在实现。有些人会说,值得调用继承的Create,因为Embarcadero将来可能会为TObject.Create添加一个实现,但我怀疑这是真的;它会破坏不调用继承的Create的现有代码。不过,我认为这是一个好主意,因为一致的原因。


Should I call "inherited" in the constructor of a class derived from TObject or TPersistent?

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;

解决方案

Yes. It does nothing, true, but it's harmless. I think there is value in being consistent about always calling the inherited constructor, without checking to see if there is, in fact, an implementation. Some will say that it's worth calling inherited Create because Embarcadero might add an implementation for TObject.Create in the future, but I doubt this is true; it would break existing code which does not call inherited Create. Still, I think it is a good idea to call it for the reason of consistency alone.

这篇关于使用继承于“创建”一个TObject的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆