简体   繁体   中英

How to get invocation list of an explicit event in C#

I can define an event with the following:

public event msg_callback event_PingMessage; 

and get the invocation list of an event with the following:

MulticastDelegate event_delegate = (MulticastDelegate)this.GetType().GetField(event_name,
                                BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField).GetValue(this);

foreach (var handler in event_delegate.GetInvocationList())
{
    // use handler() here 
}

But, if I define my event_PingMessage as an explicit event, like:

    private msg_callback explicitEvent;
    public event msg_callback event_PingMessage
    {
        add
        {
            explicitEvent += value;
            int i = 0; 

        }
        remove
        {
            explicitEvent -= value;
        }
    }

the MulticastDelegate event_delegate = ... line throws an exception:

Object reference not set to an instance of an object.

How can I .GetInvocationList() for my explicit events?

You can just use explicitEvent.GetInvocationList() . explicitEvent is the equivalent of the field returned by your GetField(...) call for a field-like event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM