首页 > 解决方案 > 我如何在 DELPHI 中任何单元的初始化块内调用任何过程或函数

问题描述

我试图在我的单元的初始化块中调用一个过程,因为我希望该过程在应用程序启动时执行,然后再执行其他任何操作。编译器显示此错误:

[dcc32 Error] Unit2.pas(152): E2076 This form of method call only allowed for class methods or constructor

这就是我的程序的样子

procedure TForm2.initilize()   ;
      begin
  ListBox2.Items.Add('Mohit');
  ListBox2.Items.Add('Raghav');
  ListBox2.Items.Add('Maninder');
  ListBox2.Items.Add('Tanya');
      end;

这是在初始化中进行调用的地方

initialization
begin
     TForm2.initilize();
end;

标签: delphiinitializationpascal

解决方案


我更喜欢经典的构造函数。优点是您甚至可以对框架使用相同的方法,因为框架没有 OnCreate。

interface
...
type
TForm2 = class(TForm)
private
  procedure initialize;
  ...
public
  constructor Create(AOwner: TComponent); override;
  ...
end;

implementation

constructor TForm2.Create(AOwner: TComponent);
begin
  inherited;
  initialize;
end;

推荐阅读