开发者

What so special about events when they are just delegates in C#?

I am learning about events in C#. I found out 开发者_运维技巧that they are just multicast delegates.

My confusion is that why do we have "event" keyword while they are delegate, can't we do

the same as we use delegates.


Events are essentialy properties whose types are delegates. The intent of the event keyword is to denote what are actually events that an object fires (i.e. callback functions), versus properties that simply hold a delegate. This distinction is important to GUI tools that need to show you what events an object can fire. Of course this could have been done with an annotation, but that wasn't the design that was chosen for C#.

In a recent interview, Anders Hejlsberg (the creator of C#) mentions that if he were designing it over again, he would probably not make events so special.


the event keyword is a modifier for a delegate declaration that allows it to be included in an interface, constraints it invocation from within the class that declares it, provides it with a pair of customizable accessors (add and remove) and forces the signature of the delegate (when used within the .NET framework).

see here for a nice explanation.


Events restricts how the list of delegates can be manipulated as you can only add and remove delegates via the += and -= operators. Delegates on the other hand do not carry this restriction so given the defintions below.

public event DelegateType Events;
public DelegateType Delegates;

You can do the following

instance.Delegates = null; // clear the list of delegates

but the compiler will prevent you from doing

instance.Events = null; // doesn't compile

When compiled the Events field is actually private despite its declaration as public and the compiler simply adds add/remove methods for manipulating the list.


A member declared with the keyword event really is a MulticastDelegate. The only specialty about it is that although you declare the event public you can only invoke the event / delegate from within your class. This is because the compiler generates a private field storing the delegate and public methods to subscribe to and unsubscribe from the event. If you directly used a Delegate anyone from the outside is allowed to invoke the delegate at any time.

So an event is really just a nifty encapsulation of a delegate.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜