我希望创建一个像“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,这又破坏了你的字符串列表.