我希望创建类似“TOwnedStringList”(类名是虚构的)的东西,我可以构造为:
sl := TOwnedStringList.Create(Self);
sl.Sorted := True;
sl.Duplicates := dupIgnore;
sl.Add(...);
// etc...
其中Self
可以是Form(例如),以便所有者将自动释放StringList。
我希望能够避免自己打电话给sl.Free
。
这可能吗?
答案 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
具有弹性。