Forked from michaelbartnett/HashableWeakRefOfT.cs
Last active
August 29, 2015 14:00
-
-
Save mpsenn/11269927 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class HashableWeakRef<T> : IEquatable<HashableWeakRef<T>> where T : class | |
{ | |
private int hash; | |
private WeakReference weakRef; | |
public T Target { get { return (T) weakRef.Target; } } | |
public HashableWeakRef(T target) | |
{ | |
weakRef = new WeakReference(target); | |
hash = target.GetHashCode(); | |
} | |
public override int GetHashCode() | |
{ | |
return hash; | |
} | |
public override bool Equals(object other) | |
{ | |
if (other is HashableWeakRef<T>) { | |
return this.Equals((HashableWeakRef<T>) other); | |
} | |
return false; | |
} | |
public bool Equals(HashableWeakRef<T> other) | |
{ | |
return (this == other); | |
} | |
public static bool operator ==(HashableWeakRef<T> a, HashableWeakRef<T> b) | |
{ | |
if(a.hash != b.hash) { | |
return false; | |
} | |
var tmpTargetA = (T) a.weakRef.Target; | |
var tmpTargetB = (T) b.weakRef.Target; | |
if (tmpTargetA == null || tmpTargetB == null) { | |
return false; | |
} | |
return tmpTargetA == tmpTargetB; | |
} | |
public static bool operator !=(HashableWeakRef<T> a, HashableWeakRef<T> b) | |
{ | |
return !(a == b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment