delphi – 如何创建一个TStringList后代与所有者将自动释放TStringList?

前端之家收集整理的这篇文章主要介绍了delphi – 如何创建一个TStringList后代与所有者将自动释放TStringList?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望创建一个像“TOwnedStringList”(类名是一个小说),我可以构造为:
sl := TOwnedStringList.Create(Self);
sl.Sorted := True;
sl.Duplicates := dupIgnore; 
sl.Add(...);
// etc...

其中Self可以是一个Form(例如),所以所有者将自动释放StringList.
我想要能够避免自己调用sl.Free.

这可能吗?

解决方法

那会有点混乱你需要做这样的事情.
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;

基本上,您创建一个由owner所拥有的TOwnerComponent的实例,该实例将传递给TOwnedStringList.Create.当该拥有者去世时,它会破坏TOwnerComponent,这又破坏了你的字符串列表.

代码对于在字符串列表中调用的显式Free是有弹性的.

原文链接:https://www.f2er.com/delphi/101191.html

猜你在找的Delphi相关文章