X hits on this document

770 views

0 shares

0 downloads

0 comments

252 / 396

Chapter ‎18   Unsafe code

An event can be used as the left-hand operand of the += and -= operators (§‎7.13.3). These operators are used, respectively, to attach event handlers to or to remove event handlers from an event, and the access modifiers of the event control the contexts in which such operations are permitted.

Since += and -= are the only operations that are permitted on an event outside the type that declares the event, external code can add and remove handlers for an event, but cannot in any other way obtain or modify the underlying list of event handlers.

In an operation of the form x += y or x -= y, when x is an event and the reference takes place outside the type that contains the declaration of x, the result of the operation has type void (as opposed to having the type of x, with the value of x after the assignment). This rule prohibits external code from indirectly examining the underlying delegate of an event.

The following example shows how event handlers are attached to instances of the Button class:

public delegate void EventHandler(object sender, EventArgs e);

public class Button: Control { public event EventHandler Click; }

public class LoginDialog: Form { Button OkButton; Button CancelButton;

public LoginDialog() { OkButton = new Button(...); OkButton.Click += new EventHandler(OkButtonClick); CancelButton = new Button(...); CancelButton.Click += new EventHandler(CancelButtonClick); }

void OkButtonClick(object sender, EventArgs e) { // Handle OkButton.Click event }

void CancelButtonClick(object sender, EventArgs e) { // Handle CancelButton.Click event } }

Here, the LoginDialog instance constructor creates two Button instances and attaches event handlers to the Click events.

10.7.1 Field-like events

Within the program text of the class or struct that contains the declaration of an event, certain events can be used like fields. To be used in this way, an event must not be abstract or extern, and must not explicitly include event-accessor-declarations. Such an event can be used in any context that permits a field. The field contains a delegate (§‎15) which refers to the list of event handlers that have been added to the event. If no event handlers have been added, the field contains null.

In the example

public delegate void EventHandler(object sender, EventArgs e);

public class Button: Control { public event EventHandler Click;

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.239

Document info
Document views770
Page views770
Page last viewedSat Dec 03 04:54:12 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments