我正在用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;
上面的代码可以很好地工作,并且可以达到预期的效果。但是我对从构造函数调用析构函数感到不好,即使这是一个不同的实例。这是正确的方法吗?我还需要考虑其他事项吗?
非常感谢。
我认为您的解决方案很好。销毁构造函数中的对象没有问题。您可以将代码更改为以下代码,因此无需显式创建TMyForm实例。 (未经测试的代码)
interface
uses Forms;
type
TMyForm = class(TForm)
private
class var instance : TMyForm;
class function GetCurInstance() : TMyForm; static;
public
constructor Create(); virtual;
destructor Destroy(); override;
class property CurInstance: TMyForm read GetCurInstance;
end;
implementation
uses SysUtils;
constructor TMyForm.Create();
begin
inherited Create(nil);
end;
destructor TMyForm.Destroy();
begin
FreeAndNil(instance);
inherited Destroy;
end;
class function TMyForm.GetCurInstance():TMyForm;
begin
if(instance=nil) then begin
instance:=TMyForm.Create();
end;
Result:=instance;
end;