Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Created February 18, 2014 14:08
Show Gist options
  • Save hagbarddenstore/9071658 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/9071658 to your computer and use it in GitHub Desktop.
void Main()
{
var testApplication = new TestApplication();
var eventInfo = testApplication.GetType().GetEvents().First();
EventHandlerPusher.AddEventHandler(testApplication, eventInfo, MyEventHandler);
EventHandlerPusher.AddEventHandler(testApplication, eventInfo, MyEventHandler);
testApplication.FireEvent();
}
class EventHandlerPusher
{
private static readonly IDictionary<Type, MethodInfo> _cachedWrappers = new Dictionary<Type, MethodInfo>();
public static void AddEventHandler(object instance, EventInfo eventInfo, EventHandler<EventArgs> eventHandler)
{
MethodInfo wrap;
var eventType = eventInfo.EventHandlerType.GenericTypeArguments.First();
if (!_cachedWrappers.TryGetValue(eventType, out wrap))
{
wrap = typeof(EventHandlerPusher).GetMethod("Wrap", BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(eventType);
_cachedWrappers.Add(eventType, wrap);
}
wrap.Invoke(null, new object[] { instance, eventInfo, eventHandler });
}
private static void Wrap<T>(object instance, EventInfo eventInfo, EventHandler<EventArgs> eventHandler)
where T : EventArgs
{
var wrapper = new EventHandler<T>((sender, e) => { eventHandler(sender, e); });
eventInfo.AddEventHandler(instance, wrapper);
}
}
void MyEventHandler(object sender, EventArgs e)
{
Console.WriteLine("Event fired!");
}
class TestApplication
{
public event EventHandler<MyEventArgs> SomeEvent;
public void FireEvent()
{
if (SomeEvent != null)
{
SomeEvent(this, new MyEventArgs());
}
}
}
class MyEventArgs : EventArgs
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment