假设我有两个WeakReference
实例,我想看看它们是否指向同一个对象。您可以想象两种情况,一种是两个引用都指向同一对象:
SomeClass a = 1;
var wr1 = new WeakReference(a);
var wr2 = new WeakReference(a);
还有一个他们没有:
SomeClass a = 1;
SomeClass b = 1;
var wr1 = new WeakReference(a);
var wr2 = new WeakReference(b);
有没有办法确定它们是否指向同一个对象而不会陷入不安全的上下文? WeakReference.GetHashCode()
在这两种情况下返回不同的值,我找不到任何其他可能相关的成员。
对基础对象的目标属性引用。
试试这个:
wr1.Target == wr2.Target
您可以使用
重载运算符为WeakReference
创建自己的包装器。喜欢这个:
public interface IWeakReferenceDecorator<T> where T : class
{
public void SetTarget(T target);
public bool TryGetTarget(out T target);
}
public class TransientWeakReference<T> : IWeakReferenceDecorator<T> where T : class
{
private readonly WeakReference<T> _weakReference;
public TransientWeakReference(T target)
{
_weakReference = new WeakReference<T>(target);
}
public TransientWeakReference(T target, bool trackResurrection)
{
_weakReference = new WeakReference<T>(target, trackResurrection);
}
public TransientWeakReference(WeakReference<T> weakReference)
{
_weakReference = weakReference;
}
public void SetTarget(T target)
{
_weakReference.SetTarget(target);
}
public bool TryGetTarget(out T target)
{
return _weakReference.TryGetTarget(out target);
}
public static bool operator ==(TransientWeakReference<T> ref1, TransientWeakReference<T> ref2)
{
if (ref1 is null && ref2 is null)
return true;
return ref1 is not null &&
ref2 is not null &&
ref1._weakReference.TryGetTarget(out var target1) &&
ref2._weakReference.TryGetTarget(out var target2) &&
target1 == target2;
}
public static bool operator !=(TransientWeakReference<T> ref1, TransientWeakReference<T> ref2)
{
return !(ref1 == ref2);
}
public override bool Equals(object obj)
{
return obj != null && GetHashCode() == obj.GetHashCode();
}
public override int GetHashCode()
{
return (_weakReference != null && _weakReference.TryGetTarget(out var target) ? target.GetHashCode() : 0);
}
此示例不适用于序列化,因为它本质上不会ISerializable
。因此,如果您还需要序列化此类对象,请添加正确使用ISerializable
接口