Delphi

TComponentList mit Auto-Remove

Aus dieser Komponenten-Liste verschwinden Referenzen automatisch, wenn zugehörige Objekte von irgendwem irgendwo freigegeben werden.

type
  TComponentList<T: TComponent> = class(TObjectList<T>)
  strict private type
    TNotify = class(TComponent)
      FParent: TComponentList<T>;
      procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    end;
  strict private
    FNotify: TNotify;
  protected
    procedure Notify(const Value: T; Action: TCollectionNotification); override;
  public
    destructor Destroy; override;
  end;

destructor TComponentList<T>.Destroy;
begin
  FNotify.Free;
  inherited;
end;

procedure TComponentList<T>.Notify(const Value: T; Action: TCollectionNotification);
begin
  inherited;
  if not Assigned(FNotify) then begin
    FNotify := TNotify.Create(nil);
    FNotify.FParent := Self;
  end;
  if Action = cnAdded then
    FNotify.FreeNotification(Value)
  else if not Contains(Value) then
    FNotify.RemoveFreeNotification(Value);
end;

procedure TComponentList<T>.TNotify.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited;
  if Operation = opRemove then
    while FParent.Extract(AComponent) <> nil do ;
end;
[add] TComponentList gibt es schon länger, versteckt sich heimlich in System.Contnrs, aber als generische Variante fehlt es dennoch. Praktsicher Weise heißt es auch gleich.

blödkönnte besser seinganz OKgutsuper duper (noch nicht abgestimmt)  
Loading...

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert