我正在尝试创建我所理解的Delphi 2007中的类工厂.我想将派生类类型传递给函数并让它构造该类类型的对象.
我找到了一些很好的参考资料,例如How can I create an Delphi object from a class reference and ensure constructor execution?,但我仍然无法让它工作得很好.在下面的测试中,我无法让它调用派生构造函数,即使调试器告诉我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.