Ray
Ray

Reputation: 46585

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?

Upvotes: 6

Views: 2029

Answers (1)

Ray
Ray

Reputation: 46585

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});

Upvotes: 19

Related Questions