Alternative to EventInfo.AddEventHandler for non-public event
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 EventHan开发者_运维知识库dler(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});
精彩评论