开发者

Alternative to EventInfo.AddEventHandler for non-public event

开发者 https://www.devze.com 2023-03-14 14:04 出处:网络
I have a class that waits for events to happen. I\'m using reflection to connect the event handler to the object like so:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号