Delphi 窗体以自定义构造函数作为主窗体?

标签 delphi constructor tform

我想要一个从具有自定义构造函数的 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/

相关文章:

delphi - 我不知道是否需要或如何实现接口(interface)的这 3 个基本方法

java - 使用构造函数创建帐户并登录

delphi - 为什么 TForm.Handle 是 getter 而不是字段?

delphi - 在 delphi TForm 类中仅出现 'public' 错误

delphi - TForm 上的 RTTI GetFields 和 GetAttributes

multithreading - 为什么 WaitForMultipleObjects 在使用多个线程句柄时会失败?

delphi - 我可以更改 Delphi XE2 中 watch 的顺序吗?

delphi - 以两种不同的方式显示表单

c++ - 调用"Use of deleted function"move 构造函数时为`std::unique_ptr`?

c# - 如何为我编写的类编写数组样式的初始化程序?