为什么在通过元类类工厂实例化时不调用派生构造函数?
我正在尝试在 Delphi 2007 中创建我所理解的类工厂。我想将派生类类型传递到函数中并让它构造该类类型的对象。
我找到了一些很好的参考,例如 如何从类引用创建 Delphi 对象并确保构造函数执行? ,但我仍然无法让它正常工作。在下面的测试中,即使调试器告诉我 oClass 是 TMyDerived,我也无法让它调用派生构造函数。
我想我对这里的一些基本问题感到困惑,需要一些解释。谢谢。
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.
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.
I've found some good references, such as How can I create an Delphi object from a class reference and ensure constructor execution?, 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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您忽略了在派生类构造函数上指定
override
。 (我预计编译器会发出有关隐藏基类方法的警告。)添加该内容,您应该会看到调用了TMyDerived.Create
。由于您的构造函数不带参数,另一种选择是放弃虚拟构造函数并仅重写
AfterConstruction
。You neglected to specify
override
on the derived class constructor. (I would have expected a warning from the compiler about hiding the base-class method.) Add that, and you should seeTMyDerived.Create
called.An alternative, since your constructors take no parameters, is to forgo virtual constructors and just override
AfterConstruction
.