I have a class that waits for events to happen.
I'm using reflection to connect the event handler to the object like so:
public EventMonitor(object eventObject, string eventName)
{
_eventObject = eventObject;
_waitEvent = eventObject.GetType().GetEvent(eventName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
_handler = new EventHandler(SetEvent);
_waitEvent.AddEventHandler(eventObject, _handler);
}
This all works fine, except I have an event that isn't public (it's internal and exposed to this testing assembly through InternalsVisibleToAttribute).
The AddEventHandler call fails with "Cannot add the event handler since no public add method exists for the event."
Is there a workaround I can use?
Don't know how I missed this method before, but here's the solution in case someone else has the same problem
Replace the AddEventHandler call with:
var addMethod = _waitEvent.GetAddMethod(true);
addMethod.Invoke(eventObject, new[] {_handler});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With