Delphi Form以自定义构造函数为主要形式?

ss2*_*006 2 delphi constructor tform

我想要一个从具有自定义构造函数的BaseForm派生的MainForm.由于这是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;  
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 8

Application.CreateForm()无法调用reintroduce'd构造函数.在创建新对象时,它会调用TComponent.Create()构造函数并期望多态来调用任何派生的构造函数.通过reintroduce自定义构造函数,您不是多态调用链的一部分.reintroduce公开一个全新的方法,该方法与继承的方法具有相同的名称,但与之无关.

要做你正在尝试的事情,不要使用reintroduce你的构造函数.在Base窗体中创建一个单独的构造函数,然后让MainForm override成为标准构造函数并调用自定义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;  
Run Code Online (Sandbox Code Playgroud)

  • 带参数的构造函数的优点是你必须**传递一些东西,所以你不能忘记传递所需的设置.设置属性可能会被遗忘.这不是因为人们想要节省几行输入,而只是因为它是更好的策略,IMO. (2认同)