Click here to Skip to main content
15,892,072 members
Articles / Programming Languages / C#

Tweaked Events

Rate me:
Please Sign up or sign in to vote.
4.83/5 (12 votes)
18 Dec 2010MIT18 min read 34.8K   289   41  
Framework for customizing events. Comes with Weak Events and Synced Events
using System;
using System.Reflection;

namespace JpLabs.TweakedEvents
{
	public abstract class BaseEventEntry<TEH> : IEventEntry<TEH> where TEH : class
	{
		private static readonly MethodInfo DynamicInvoke_Info;
		
		static BaseEventEntry()
		{
			// Make sure TEH is an acceptable EventHandler
			Type eventArgsType;
			GenericArgumentValidator.ValidateEventHandler<TEH>(out eventArgsType);
			
			//Get the MethodInfo for DynamicInvoke<TEventArgs>
			MethodInfo genericDynamicInvoke = typeof(BaseEventEntry<TEH>).GetMethod("DynamicInvoke", BindingFlags.Instance | BindingFlags.NonPublic);
			DynamicInvoke_Info = genericDynamicInvoke.MakeGenericMethod(eventArgsType);
		}
		
		// Abstract Methods / IEventEntry<TEH> members		
		abstract public bool Equals(IEventEntry other);
		abstract public bool EqualsHandler(TEH handler);
		abstract public bool Invoke(object sender, EventArgs e);
		abstract public void Dispose();
		abstract public bool IsDisposed { get; }
		
		// Conversion to a TEventHandler delegate
		public static implicit operator TEH(BaseEventEntry<TEH> entry)
		{
			if (entry == null) return null;
			
			return entry.ToEventHandler();
		}

		public TEH ToEventHandler()
		{
			return (TEH)(object)Delegate.CreateDelegate(typeof(TEH), this, DynamicInvoke_Info);
		}

		private void DynamicInvoke<TEventArgs>(object sender, TEventArgs e) where TEventArgs : EventArgs
		{
		    ((IEventEntry)this).Invoke(sender, e);
		}
	}
}

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.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior) ThoughtWorks
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions