|
using System;
using System.Reflection;
namespace JpLabs.TweakedEvents
{
//public interface IWeakDelegate : IEquatable<IWeakDelegate>, IEquatable<Delegate>
//{
// bool IsDead();
//}
//internal class MulticastWeakDelegate : IWeakDelegate
//{
//}
public class SinglecastWeakDelegate : IEquatable<SinglecastWeakDelegate>, IEquatable<Delegate>
{
public readonly MethodInfo TargetMethod;
public readonly WeakReference TargetReference;
//public static IWeakDelegate CreateWeakDelegate(Delegate dlg)
//{
// if (dlg == null) throw new ArgumentNullException("dlg");
// var invocList = dlg.GetInvocationList();
// if (invocList.Length > 1) throw new NotImplementedException();
// return new SinglecastWeakDelegate(dlg);
//}
internal SinglecastWeakDelegate(Delegate dlg)
{
this.TargetReference = dlg.Target != null ? new WeakReference(dlg.Target) : null;
this.TargetMethod = dlg.Method;
}
public bool IsDead()
{
return TargetReference != null && !TargetReference.IsAlive;
}
public static bool operator ==(SinglecastWeakDelegate wd1, SinglecastWeakDelegate wd2)
{
if (((object)wd2) == null) return ((object)wd1) == null;
if (((object)wd1) == null) return ((object)wd2) == null;
return wd1.Equals(wd2);
}
public static bool operator !=(SinglecastWeakDelegate wd1, SinglecastWeakDelegate wd2)
{
if (((object)wd2) == null) return ((object)wd1) != null;
if (((object)wd1) == null) return ((object)wd2) != null;
return !wd1.Equals(wd2);
}
public override int GetHashCode()
{
int hashCode = TargetMethod.GetHashCode();
if (TargetReference != null) hashCode ^= TargetReference.GetHashCode(); //bitwise XOR
return hashCode;
}
public override bool Equals(object obj)
{
if (obj is SinglecastWeakDelegate) return Equals((SinglecastWeakDelegate)obj);
return false;
}
public bool Equals(SinglecastWeakDelegate other)
{
return (
((object)other) != null
) && (
TargetReference.WeakRefEquals(other.TargetReference) //Compare target object
) && (
this.TargetMethod == other.TargetMethod //Compare method info
);
}
public bool Equals(Delegate dlg)
{
return (
//Compare target object
(this.TargetReference == null)
? (dlg.Target == null) //method is static
: (dlg.Target == this.TargetReference.Target) //method is not static
) && (
//Compare method info
this.TargetMethod == dlg.Method
);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.