开发者

What does the event keyword really do?

public delegate void SecondChangedHa开发者_如何学JAVAndler(
        object clock, 
        TimeInfoEventArgs timeInformation);

    public event SecondChangedHandler SecondChanged;

I have written a clock based on this article. Now if i remove the event keyword i get the same result, so what does event really do?


It's compiled differently. It makes it so someone can't do

mySecondChangedHandler.SecondChanged = SomeMethod(...); //overwrite
mySecondChangedHandler.SecondChanged(...); //invoke

but only

mySecondChangedHandler.SecondChanged += SomeMethod(...);
mySecondChangedHandler.SecondChanged -= SomeMethod(...);


The event keyword creates a private delegate field, and a pair of public event accessors called add_EventName and remove_EventName. (details)

This means that writing EventName inside the class returns the delegate instance, allowing you to call or inspect the event handlers.

Outside the class, EventName doesn't really exist; all you can do is write EventName += something and EventName -= something, and the compiler will convert it into calls to the accessors. (like a property)

For more details, see this series of blog posts.


The event keyword does two things

  • It supplied permissions. Only the class can raise the event, however any external method can invoke the raw delegate
  • It provides metadata which can be used for designers and the like


The event keywords means only methods on the instance that hosts the SecondChanged field can invoke it. External attempts will fail.


The event keyword creates a pair of accessors for a delegate. These are effectively two methods (add and remove) that are called when you subscribe or unsubscribe from the event.

In your case, you're creating a "field-like event". The compiler makes a delegate behind the scenes, and allows you to subscribe and unsubscribe from it's invocation list. This means that you have all of the functionality of a delegate, but you're restricting access so that that outside world can "handle" the event, but not raise the event (invoke the delegate).

You can, however, also explicitly create your own accessors for an event, and these can do other things (though that's not typically recommended unless there is a good reason to do so).


Quote from C# lang reference about keyword event,

Events are a special kind of multicast delegate that can only be invoked from within the class or struct where they are declared (the publisher class).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜