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

CHAPTER 16 EVENTS

Events Are Like Delegates

The preceding chapter covered delegates. Many aspects of events are similar to those of delegates. In fact, an event is like a simpler delegate that is specialized for a particular use. Figure 16-1 illustrates that, like a delegate, an event has methods registered with it and invokes those methods when it is invoked.

The following are some important terms related to events:

Raising an event: The term for invoking or firing an event. When an event is raised, all the methods registered with it are invoked—in order.

Publisher: A class or struct that makes an event available to other classes or structs for their use.

Subscriber: A class or struct that registers methods with a publisher.

Event handler: A method that is registered with an event. It can be declared in the same class or struct as the event or in a different class or struct.

Figure 16-1. Publishers and subscribers

392

CHAPTER 16 EVENTS

An Event Has a Private Delegate

There’s good reason for the similarities in the behaviors of delegates and events. An event contains a private delegate, as illustrated in Figure 16-2. The important things to know about an event’s private delegate are the following:

An event gives structured access to its privately controlled delegate.

Unlike the many operations available with a delegate, with an event you can only add, remove, and invoke event handlers.

When an event is raised, it invokes the delegate, which sequentially calls the methods in the invocation list.

Notice in Figure 16-2 that only the += and -= operators are sticking out to the left of the event. This is because they are the only operations allowed on an event.

Figure 16-2. An event has an encapsulated delegate

Figure 16-3 illustrates the runtime view of a publisher class with an event called Elapsed. ClassA and ClassB, on the right, each has an event handler registered with Elapsed. Inside the event you can see the delegate referencing the two event handlers. Besides the event, the publisher also contains the code that raises the event.

Figure 16-3. Structure and terminology of a class with a timer event

393

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