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

CHAPTER 16 EVENTS

Raising an Event

The event member itself just holds the event handlers that need to be invoked. Nothing happens with them unless the event is raised. You need to make sure there is code to do just that, at the appropriate times.

For example, the following code raises event Elapsed. Notice the following about the code:

Before raising the event, the code compares it to null, to see whether it contains any event handlers. If the event is null, it is empty.

Raising the event itself is like invoking a function.

Use the name of the event, followed by the parameter list enclosed in parentheses.

The parameter list must match the delegate type of the event.

if (Elapsed != null)

//

Make sure

there are methods to execute.

Elapsed (source, args);

//

Raise the

event.

 

 

 

 

Event name

Parameter list

 

 

 

Putting together the event declaration and the code to raise the event gives the following class declaration for the publisher. The code contains two members: the event and a method called OnOneSecond, which raises the event.

public class MyTimerClass

 

 

{

 

 

 

 

 

public event EventHandler Elapsed;

// Declare the event.

private void OnOneSecond(object source, EventArgs args)

{

if (Elapsed != null)

// Make sure there are methods to execute.

 

 

Elapsed(source, args);

 

 

}

 

 

 

 

 

 

Raise the event.

 

 

//The following code makes sure that method OnOneSecond is called every

//1,000 milliseconds.

...

}

For now, I’ll let method OnOneSecond be somehow, mysteriously, called once every second. Later in the chapter I’ll show you how to make this happen. But for now, remember these important points:

The publisher class has an event as a member.

The class contains the code to raise the event.

397

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