Created
February 18, 2014 14:00
-
-
Save hagbarddenstore/9071520 to your computer and use it in GitHub Desktop.
This file contains 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
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