Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Created February 18, 2014 14:00
Show Gist options
  • Save hagbarddenstore/9071520 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/9071520 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);
testApplication.FireEvent();
}
class EventHandlerPusher
{
public static void AddEventHandler(object instance, EventInfo eventInfo, EventHandler<EventArgs> eventHandler)
{
var wrapperType = typeof(EventHandlerPusher).GetMethod("Wrap", BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(eventInfo.EventHandlerType.GenericTypeArguments.First());
var wrapper = (Delegate)wrapperType.Invoke(null, new object[] { eventHandler });
eventInfo.AddEventHandler(instance, wrapper);
}
private static EventHandler<T> Wrap<T>(EventHandler<EventArgs> eventHandler)
where T : EventArgs
{
return new EventHandler<T>((sender, e) => { eventHandler(sender, e); });
}
}
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