以自定义构造函数为主要形式的Delphi Form? [英] Delphi Form with custom constructor as the mainform?

查看:190
本文介绍了以自定义构造函数为主要形式的Delphi Form?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个MainForm,该MainForm是从具有自定义构造函数的BaseForm派生的.由于这是Mainform,因此它是通过调用* .dpr文件中的 Application.CreateForm(TMyMainForm,MyMainForm)创建的.但是,在表单创建期间不会调用我的自定义构造函数.

I want to have a MainForm that is derived from a BaseForm that has a custom constructor. Since this is the Mainform, it is created by a call to Application.CreateForm(TMyMainForm, MyMainForm) in the *.dpr file. However, my custom constructor is not called during form creation.

很明显,如果我调用 MyMainForm:= TMyMainForm.Create(AOwner),它就可以正常工作.我可以不使用以自定义构造函数为主要表单的表单吗?

Obviously, it works fine, if I call MyMainForm := TMyMainForm.Create(AOwner). Can I not use a form with custom constructor as the main form ?

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()无法调用reintroduce的构造函数.创建新对象时,它将调用TComponent.Create()构造函数,并期望多态性可以调用任何派生的构造函数.通过reintroduce'ing您的自定义构造函数,您就不会属于多态调用链. reintroduce公开了一种全新的方法,该方法与继承的方法具有相同的名称,但与之无关.

Application.CreateForm() cannot call a reintroduce'd constructor. When creating a new object, it calls the TComponent.Create() constructor and expects polymorphism to call any derived constructors. By reintroduce'ing your custom constructor, you are not part of the polymorphic call chain. reintroduce exposes a completely new method that simply has the same name as an inherited method but is not related to it.

要做您想做的事情,请不要对构造函数使用reintroduce.在您的Base表单中创建一个单独的构造函数,然后将MainForm override作为标准构造函数,并调用您的自定义Base构造函数,例如:

To do what you are attempting, don't use reintroduce for your constructors. Create a separate constructor in your Base form, and then have your MainForm override the standard constructor and call your custom Base constructor, eg:

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 Form?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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