It is an expansion of the event declaration used previously that includes add and
remove code blocks. It is similar to the get and set code blocks that programmers can use to
define properties in C#. The result is the following Click event:
public event EventHandler Click
{
add
{
Events.AddHandler(ClickEvent, value);
}
remove
{
Events.RemoveHandler(ClickEvent, value);
}
}
The first thing to notice is the event declaration itself. It is declared with an event keyword,
delegate type, name, and accessibility modifier as before. The new functionally is added via
code blocks below the declaration. The add and remove code blocks handle the delegate registration
process in whatever manner they see fit. In this case, these code blocks are passed the
delegate reference via the value keyword to accomplish their assigned tasks.
The code in our Click event uses the Events collection to add the delegate via AddHandler
or to remove the delegate via RemoveHandler. ClickEvent is the access key used to identify the
Click delegates in our Events collection, keeping like event handlers in separate buckets.
After we declare our event with its event subscription code, we need to define our OnClick
method to raise the event. The code uses the Events collection and our defined key object to get
the Click delegate and raise the event to subscribers:
protected virtual void OnClick(EventArgs e)
{
EventHandler clickEventDelegate = (EventHandler)Events[ClickEvent];
if (clickEventDelegate != null)
{
clickEventDelegate(this, e);
}
}
The first step is to pull the delegate of type EventHandler from the Events collection.
Pages:
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312