开发者

The Main Purpose of Events in C#

I've been examining one of my c# books and I just saw a sen开发者_JS百科tence about Events in C#:

 The main purpose of events is to prevent subscribers from interfering with each other.

Whatever it means, yeah actually events are working pretty much like delegates.

I've been wondering why I should use events instead of delegates.

So is there any one who can explain the bold part?

Thanks in advance.


The choice wouldn't really be between a delegate and an event - they're completely different things. You could, however, expose a public property or a public field which had a delegate type. I assume that's what you really mean.

Suppose Button.Click were a public field or property instead of an event. One piece of code could then subscribe to an event, and another could then write:

// Invalid with events, valid with properties
button.Click = null;

thus wiping out the original event handler. Likewise other code would also be able to invoke the event handlers:

// Invalid with events, valid with properties
button.Click(this, EventArgs.Empty);

even though the button hadn't been clicked. This is clearly a violation of encapsulation. The only reason to expose Click to other code is to allow them to register interest in button clicks and register disinterest later - and those are exactly the abilities that events provide.

Think of events as syntactic sugar around two methods. For example, if we didn't have events then Button would probably have:

public void AddClickHandler(EventHandler handler)
public void RemoveClickHandler(EventHandler handler)

The violation of encapsulation goes away, but you lose some of the convenience - and everyone has to write their own methods like that. Events simplify this pattern, basically.


An event can only be invoked by the class defining it, whereas a delegate can be invoked from whomever has access to it. This here is what I believe the bold text means.

Also, an event can be defined in an interface, whereas a delegate cannot (as you would declare the delegate as a field).

I recommend giving this link a read, as it explains it quite nicely and has a few more examples other than the above mentioned.


You can set a delegate to NULL which causes it to 'forget' every function that is subscribed to it.


You can add as many eventhandler to your event as you want.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜