[英]Why doesn't the derived constructor get called when instantiating via a metaclass class factory?
I'm trying to create what I understand to be a Class Factory in Delphi 2007. I want to pass a derived class type into a function and have it construct an object of that class type. 我正在尝试创建我所理解的Delphi 2007中的类工厂。我想将派生类类型传递给函数并让它构造该类类型的对象。
I've found some good references, such as How can I create an Delphi object from a class reference and ensure constructor execution? 我找到了一些很好的参考资料,例如如何从类引用中创建Delphi对象并确保构造函数执行? , but I still can't get it to work quite right. ,但我还是不能让它工作得很好。 In the test below, I can't get it to call the derived constructor, even though the debugger tells me that oClass is TMyDerived. 在下面的测试中,我无法让它调用派生构造函数,即使调试器告诉我oClass是TMyDerived。
I think I'm confused about something fundamental here and could use some explanation. 我觉得我对这里的一些基本内容感到困惑,可以使用一些解释。 Thanks. 谢谢。
program ClassFactoryTest;
{$APPTYPE CONSOLE}
uses
SysUtils;
// BASE CLASS
type
TMyBase = class(TObject)
bBaseFlag : boolean;
constructor Create; virtual;
end;
TMyBaseClass = class of TMyBase;
constructor TMyBase.Create;
begin
bBaseFlag := false;
end;
// DERIVED CLASS
type
TMyDerived = class(TMyBase)
bDerivedFlag : boolean;
constructor Create;
end;
constructor TMyDerived.Create;
begin
inherited;
bDerivedFlag := false;
end;
var
oClass: TMyBaseClass;
oBaseInstance, oDerivedInstance: TMyBase;
begin
oClass := TMyBase;
oBaseInstance := oClass.Create;
oClass := TMyDerived;
oDerivedInstance := oClass.Create; // <-- Still calling Base Class constructor
end.
You neglected to specify override
on the derived class constructor. 您忽略了在派生类构造函数上指定override
。 (I would have expected a warning from the compiler about hiding the base-class method.) Add that, and you should see TMyDerived.Create
called. (我本来期望编译器发出关于隐藏基类方法的警告。)添加它,你应该看到调用了TMyDerived.Create
。
TMyDerived = class(TMyBase)
bDerivedFlag : boolean;
constructor Create; override;
end;
An alternative, since your constructors take no parameters, is to forgo virtual constructors and just override AfterConstruction
. 另一种选择,因为你的构造函数不带参数,就是放弃虚拟构造函数,然后重写AfterConstruction
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.