我想要一个从具有自定义构造函数的 BaseForm 派生的 MainForm。由于这是主窗体,因此它是通过调用 *.dpr 文件中的 Application.CreateForm(TMyMainForm, MyMainForm) 创建的。但是,在表单创建期间不会调用我的自定义构造函数。
显然,如果我调用MyMainForm := TMyMainForm.Create(AOwner),它就可以正常工作。我可以不使用带有自定义构造函数的表单作为主表单吗?
TBaseForm = class(TForm)
constructor Create(AOwner:TComponent; AName:string);reintroduce;
end;
TMyMainForm = class(TBaseForm)
constructor Create(AOwner:TComponent);reintroduce;
end;
constructor TBaseForm.Create(AOwner:TComponent);
begin;
inherited Create(AOwner);
end;
constructor TMyMainForm.Create(AOwner:TComponent);
begin;
inherited Create(AOwner, 'Custom Constructor Parameter');
end;
最佳答案
Application.CreateForm()
无法调用重新引入
的构造函数。创建新对象时,它会调用 TComponent.Create()
构造函数,并期望多态性调用任何派生构造函数。通过重新引入
您的自定义构造函数,您就不再是多态调用链的一部分。 reintroduce
公开了一个全新的方法,该方法仅与继承的方法具有相同的名称,但与之无关。
要执行您正在尝试的操作,请不要对构造函数使用reintroduce
。在您的 Base 表单中创建一个单独的构造函数,然后让您的 MainForm 覆盖
标准构造函数并调用您的自定义 Base 构造函数,例如:
TBaseForm = class(TForm)
constructor CreateWithName(AOwner: TComponent; AName: string); // <-- no reintroduce needed since it is a new name
end;
TMyMainForm = class(TBaseForm)
constructor Create(AOwner: TComponent); override; // <-- not reintroduce
end;
constructor TBaseForm.CreateWithName(AOwner: TComponent; AName: string);
begin;
inherited Create(AOwner);
// use AName as needed...
end;
constructor TMyMainForm.Create(AOwner: TComponent);
begin;
inherited CreateWithName(AOwner, 'Custom Constructor Parameter');
end;
关于Delphi 窗体以自定义构造函数作为主窗体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26132808/