Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 634
Ray Avatar asked Jun 21 '11 10:06

Ray


1 Answers

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});
like image 156
Ray Avatar answered Nov 06 '22 05:11

Ray