如何使用Owner创建一个TStringList后代,它将自动释放TStringList?

时间:2013-03-04 12:41:54

标签: delphi delphi-7

我希望创建类似“TOwnedStringList”(类名是虚构的)的东西,我可以构造为:

sl := TOwnedStringList.Create(Self);
sl.Sorted := True;
sl.Duplicates := dupIgnore; 
sl.Add(...);
// etc...

其中Self可以是Form(例如),以便所有者将自动释放StringList。 我希望能够避免自己打电话给sl.Free

这可能吗?

1 个答案:

答案 0 :(得分:13)

那会有点混乱。你需要做这样的事情。

type
  TOwnerComponent = class(TComponent)
  private
    FOwnedObject: TObject;
  public
    constructor Create(Owner: TComponent; OwnedObject: TObject);
    destructor Destroy; override;
  end;

  TOwnedStringList = class(TStringList)
  private
    FOwner: TOwnerComponent;
  public
    constructor Create(Owner: TComponent);
    destructor Destroy; override;
  end;

{ TOwnerComponent }

constructor TOwnerComponent.Create(Owner: TComponent; OwnedObject: TObject);
begin
  inherited Create(Owner);
  FOwnedObject := OwnedObject;
end;

destructor TOwnerComponent.Destroy;
begin
  FOwnedObject.Free;
  inherited;
end;

{ TOwnedStringList }

constructor TOwnedStringList.Create(Owner: TComponent);
begin
  inherited Create;
  if Assigned(Owner) then
    FOwner := TOwnerComponent.Create(Owner, Self);
end;

destructor TOwnedStringList.Destroy;
begin
  if Assigned(FOwner) and not (csDestroying in FOwner.ComponentState) then
  begin
    FOwner.FOwnedObject := nil;
    FOwner.Free;
  end;
  inherited;
end;

基本上,您创建的TOwnerComponent实例由您传递给Owner的{​​{1}}所有。当TOwnedStringList.Create死亡时,它会销毁Owner,而TOwnerComponent会破坏你的字符串列表。

代码对字符串列表中调用的显式Free具有弹性。