相关疑难解决方法(0)

在Delphi中避免嵌套try ... finally块

今天早上我有这个想法,避免嵌套尝试finally块,如下所示

procedure DoSomething;
var
  T1, T2, T3 : TTestObject;
begin
  T1 := TTestObject.Create('One');
  try
    T2 := TTestObject.Create('Two');
    try
      T3 := TTestObject.Create('Three');
      try
        //A bunch of code;
      finally
        T3.Free;
      end;
    finally
      T2.Free;
    end;
  finally
    T1.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

通过利用接口的自动引用计数,我想出了

Type  
  IDoFinally = interface
    procedure DoFree(O : TObject);
  end;

  TDoFinally = class(TInterfacedObject, IDoFinally)
  private
    FreeObjectList : TObjectList;
  public
    procedure DoFree(O : TObject);
    constructor Create;
    destructor Destroy; override;
  end;

//...

procedure TDoFinally.DoFree(O : TObject);
begin
  FreeObjectList.Add(O);
end;

constructor TDoFinally.Create;
begin
  FreeObjectList := TObjectList.Create(True);
end; …
Run Code Online (Sandbox Code Playgroud)

delphi interface try-catch

17
推荐指数
5
解决办法
1861
查看次数

标签 统计

delphi ×1

interface ×1

try-catch ×1