When does the event handler register?

We often use an event handler in C #, as shown below:

some_event+=some_event_handler; 

Does this happen at compile time or runtime? What if some_event is a static member? AFAIK, some_event contains only the address of the some_event_handler entry, and the address of the some_event_handler method can be determined at compile time. If some_event is a static member, can some_event be determined at compile time? I understand that if some_event is a member of the instance, this value will be set when the object is instantiated. Correct me if I am wrong.

Thanks a lot guys ~ :)

+6
c #
source share
4 answers

Subscription occurs at run time. It may be inside the conditional.

0
source share

We can say that this refers to delegates . A delegate variable is assigned a method dynamically. This gives us the opportunity to write plugin methods.

Regarding the instance and the static target method, just a note from C # in a nutshell

When a delegate object is assigned to an instance method, the delegate object must maintain a reference not only to the method, but also to the instance to which the method belongs. Class System.Delegate. The Target property represents this instance. (and will be null for the delegate referring to the static method).

+1
source share

If you need to track them, perhaps you need to handle events manually with the add and remove keywords. Take a look at http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx (from example 2)

And yes, I forgot, events are logged at runtime

0
source share

The code is just an operator, similar to a method call, and thus occurs in the natural flow of execution in the place where you placed it, whether inside the loop, if-statement or the like.

Thus, before the statement is executed, the event handler is not assigned to the event. It does not matter (in this context) whether the event is a static or an instance event.

You can think about how the code works by comparing it with this code:

 some_event = Delegate.Combine(some_event, some_event_handler); 

then it should be clearer that this is just a call to the main method, nothing more.

The syntax event += handler is just brief for the above code, and the compiler will translate the syntax of this method call. If you use Reflector , you can see that it is done like that.

See Delegate.Combine on MSDN.

0
source share

All Articles