在Delphi XE中将类作为过程的参数传递

Spe*_*ker 6 forms delphi factory class delphi-xe

我需要做的是这样的事情:

procedure A(type_of_form);
var form: TForm;
begin
  form := type_of_form.Create(application);
  form.showmodal;
  freeandnil(form);
end;
Run Code Online (Sandbox Code Playgroud)

我为每个动态创建的表单执行了此操作:

form1 := TForm1.Create(application);
form1.showmodal;
freeandnil(form1);
Run Code Online (Sandbox Code Playgroud)

我将在程序A中做什么更复杂,但问题在于如何使表单的创建有点笼统.也许@运营商的事情......我真的不知道.

谢谢你的任何建议!

Fra*_*ois 7

procedure Test(AMyFormClass: TFormClass);
var
 form: TForm;
begin
  form := AMyFormClass.Create(Application); // you can use nil if you Free it in here
  try
    form.ShowModal;
  finally
    form.Release; // generally better than Free for a Form
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Test(TForm2);
end;
Run Code Online (Sandbox Code Playgroud)

  • @Marcus那是对的.您需要使用虚拟构造函数通过类引用来实现实例化.否则,每次都会以"TMyForm"结束,无论类引用是什么. (2认同)