开发者

When does event handler registeration happen?

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

some_event+=some_event_handler;

Does this happen at compile time or run time? What if the some_event is static member? AFAIK, the some_event contains nothing but the entry address of some_event_handler, and the method address of some_event_handler could be determined at compile time. If some_event is a static member, could the value of the some_event be determined at compile time? 开发者_JAVA技巧I konw that if the some_event is an instance member, it's value will be setup at the creation time of the object instance. Correct me if I'm wrong.

Many thanks, guys~ :)


We can say it concerns delegates. A delegate variable is assigned a method dynamically. This gives us ability to write plugin methods.

Concerning instance and static method targets just a note from C# in 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. The System.Delegate class’s Target property represents this instance (and will be null for a delegate referencing a static method).


The subscription happens at run-time. It can be inside conditional.


If you need to track them maybe you need manual event handling with the keywords add and remove. Take a look at this http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx (from example 2 on)

And yes, i forgot, events are registered at runtime


The code is just a statement, similar to a method call, and thus occurs in the natural execution stream at the point you placed it, be it inside a loop, if-statement or similar.

As such, before the statement has executed, the event has not been assigned the event handler. It does not matter (in this context) whether the event is a static or instance event.

You can consider how the code behaves by comparing it to this code:

some_event = Delegate.Combine(some_event, some_event_handler);

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

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

See Delegate.Combine on MSDN.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜