Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 16 EVENTS

Declaring an Event

The publisher must provide the event and often provides the code to raise the event.

Creating an event is simple—it requires only a delegate type and a name. The syntax for an event declaration is shown in the following code, which declares an event called Elapsed. Notice the following about event Elapsed:

It is declared inside a class called MyTimerClass.

It accepts event handlers with the return type and signature matching the delegate type

EventHandler.

It is declared public so that other classes and structs can register event handlers with it.

class MyTimerClass

 

{

Keyword

Name of event

 

public event EventHandler Elapsed;

Delegate type

You can declare more than one event in a declaration statement by using a comma-separated list. For example, the following statement declares three events:

public event EventHandler MyEvent1, MyEvent2, OtherEvent;

Three events

You can also make events static, by including the static keyword, as shown in the following declaration:

public static event EventHandler Elapsed;

Keyword

395

CHAPTER 16 EVENTS

An Event Is a Member

A common error is to think of an event as a type, which it is not. An event is a member, and there are several important ramifications to this:

Because a member is not a type, you do not use an object-creation expression (a new expression) to create its object.

Because an event is a member

It must be declared in a class or struct, with the other members.

You cannot declare an event in a block of executable code.

An event member is implicitly and automatically initialized to null with the other members.

The Delegate Type and EventHandler

An event declaration requires the name of a delegate type. You can either declare one or use one that already exists. If you declare a delegate type, it must specify the signature and return type of the methods that will be stored by the event.

A better idea is to use the EventHandler delegate, which is a predefined delegate type used by the

.NET BCL and designated as the standard for use with events. You are strongly encouraged to use it. The following code shows what EventHandler’s declaration looks like in the BCL. The EventHandler delegate is covered in more detail later in this chapter.

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

396

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]