简体   繁体   中英

Does subscribing to an event add the handler function to the event or the event delegate's invocation list?

I am trying to debunk how many tutorials on .NET Events and Delegates are using the Event and the Delegate (believe this is an invocation list?) interchangeably when describing an object subscribing to the event.

In the case of this example code, some I've listened to have said that handlerFunction is being added to the Event's invocation list, whilst others say it is being added to to the delegate (which is what I originally thought was the (only) invocation list.)

What is the breakdown of where the subscribers are actually subscribing to?

delegate void MyEventHandler (int x, string y);

class myClass {
    public event MyEventHandler MyEvent;
}

myClass obj = new myClass();
obj.MyEvent += handlerFunction;

Delegates are immutable, not mutable. So technically when you subscribe an additional handler to an event you're not adding a handler to an existing delegate instance's invocation list, you're creating a new delegate whose invocation list will contain everything in the old delegate's invocation list plus your new handler, and assigning that new delegate to the backing store for that event.

All that said, I expect that what you're reading is just shortcutting a bit and not going into overly specific details here as it's not really a point relevant to what I expect they're actually trying to discuss at the moment.

As for the difference between thinking of it as "a delegate" versus, "an invocation list". Every delegate is just an invocation list. There isn't anything more to any delegates. There really isn't anything particularly wrong with referring to either here. Technically the event has a delegate, and subscribing the event handler is creating a new delegate that has a slightly different invocation list internally than the old delegate, and that new delegate is being assigned to the backing store. Shortcutting that to saying that adding a handler is adding a new method to the invocation list is...at least getting across the important points there. That the invocation list is held in a delegate instance isn't really particularly critical to understanding how to subscribe a handler to an event.

Defining an event creates a variable with the delegate as the type. It refers to an instance of the delegate. So you could say that the event has an invocation list or that the instance of the delegate has an invocation list, because event = instance of delegate.

This is why if you declare an event , as you have:

public event MyEventHandler MyEvent;

MyEvent is a Delegate , and you can call its GetInvocationList() method. GetInvocationList() is a member of Delegate .

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