创建新实例时销毁一个类实例

时间:2019-11-20 14:41:03

标签: class delphi instance delphi-xe2 destroy

我正在用OnClose事件中的Action = caFree在Delphi中编写MDIChild表单。现在,我希望一次只有一个表单实例。为此,我使用了一个类变量:

type
  TMyForm = class(TForm)
...
class var CurInstance: TMyForm;
...
end;

constructor TMyForm.Create();
begin
inherited Create(nil);
if Assigned(TMyForm.CurInstance) then
  TMyForm.CurInstance.Destroy

TMyForm.CurInstance := Self;
end;

destructor TMyForm.Destroy();
begin
TMyForm.CurInstance := nil;
inherited Destroy;
end;

上面的代码可以很好地工作,并且可以实现应有的功能。但是我对从构造函数调用析构函数感到不好,即使这是一个不同的实例。这是正确的方法吗?我还需要考虑其他问题吗?

非常感谢。

0 个答案:

没有答案
相关问题