VSoft.WeakReferences
v0.1.5
该单元背后的想法是提供类似的生命周期来与Delphi中的参考对象一样,就像弱referference在.NET中一样。
在循环引用方面,Delphi中的参考计数对象有一些局限性,例如tparent引用其儿童(通过iChild),而tchild引用它的父母(通过iParent)。如果我们删除了对iParent和Ichild实例的任何外部引用,而没有先让孩子删除对iParent的引用,我们最终将得到孤儿的对象。这是因为我们的Ichild和Iparent实例互相参考,因此它们永远不会被释放。
可能被引用的类别需要从TWeakReferencedObject下降。
type
TParent = class(TWeakReferencedObject, IParent)
...
end;
TChild = class(TInterfacedObject, IChild)
private
FParent : IWeakReference<IParent>;
protected
procedure SetParent(const parent : IParent);
function GetParent : IParent;
public
property Parent : IParent read GetParent write SetParent;
end;
implementation
procedure TChild.SetParent(const parent : IParent);
begin
if parent <> nil then
FParent := TWeakReference<IParent>.Create(parent)
else
FParent := nil;
end;
function TChild.GetParent : IParent;
begin
result := nil
if (FParent <> nil) and FParent.IsAlive then
result := FParent.Data;
end;
在上面的示例中,如果父对象在孩子之前被销毁,则在子对象中对其对象的弱参考将被标记为零(因此,归还返回false)。