Events
are closely related to delegates, but they are not the same thing. An event
allows code to subscribe and unsubscribe using delegate instances as event
handlers. The idea is that when an event is raised all the event handlers which
have subscribed to the event are called. Just as a property is logically just
two operations get and set, an event is also logically just two operations:
subscribe and unsubscribe.
To
declare an event and explicitly write these operations, you use syntax which
looks like a property declaration but with add and remove instead of get and
set:
Public event
EventHandler CustomEvent
{
Add
{
//Implementation goes here: “Value”
variable is the handler being
//subscribed
to the event
}
Remove
{
//Implementation goes here: “Value”
variable is the handler being
//unsubscribed
to the event
}
}
Many
events are implemented using a simple variable to store the subscribed handlers.
C#
allows these events to be created simply, as field-like events:
Public event EventHandler SimpleEvent;
This
declares both the event and a variable at the same time.
It’s
roughly equivalent to this:
private
EventHandler_hiddenField;
public event
EventHandler SimpleEvent
{
add
{
lock(this)
{
_hiddenField +=
value;
}
}
remove
{
lock(this)
{
_hiddenField -=
value;
}
}
}
Everywhere you refer to
SimpleEvent within the declaring type, the compiler actually reference
_hiddenField, which is why you’re able to raise the event by calling
SimpleEvent(). Outside the type declaration, however, SimpleEvent only refers
to the event. This duality has caused confusion for many developers – you just
need to remember that fields and events really are very different things, and
field, like events are just the compiler doing some work for you.
0 comments:
Post a Comment