Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
27
Добавлен:
25.03.2016
Размер:
14 Мб
Скачать
☆

Chapter 17 Interrupting Program Flow and Handling Events

323

Enabling Notifications with Events

You have now seen how to declare a delegate type, call a delegate, and create delegate instances. However, this is only half the story. Although by using delegates you can invoke any number of methods indirectly, you still have to invoke the delegate explicitly. In many cases, it would be useful to have the delegate run automatically when something signifi-

cant happens. For example, in the automated factory scenario, it could be vital to be able to invoke the stopMachinery delegate and halt the equipment if the system detects that a

machine is overheating.

The .NET Framework provides events, which you can use to define and trap significant actions and arrange for a delegate to be called to handle the situation. Many classes in the .NET

Framework expose events. Most of the controls that you can place on a WPF form, and the Windows class itself, use events so that you can run code when, for example, the user clicks a

button or types something in a field. You can also define your own events.

Declaring an Event

You declare an event in a class intended to act as an event source. An event source is usually a class that monitors its environment and raises an event when something significant happens. In the automated factory, an event source could be a class that monitors the temperature of each machine. The temperature-monitoring class would raise a “machine overheating” event if it detects that a machine has exceeded its thermal radiation boundary (that is, it has become too hot). An event maintains a list of methods to call when it is raised. These methods are sometimes referred to as subscribers. These methods should be prepared to handle the “machine overheating” event and take the necessary corrective action: shut down the machines.

You declare an event similarly to how you declare a field. However, because events are intended to be used with delegates, the type of an event must be a delegate, and you must prefix the declaration with the event keyword. Use the following syntax to declare an event:

event delegateTypeName eventName

As an example, here’s the StopMachineryDelegate delegate from the automated factory. It has been relocated to a new class called TemperatureMonitor, which provides an interface to

the various electronic probes monitoring the temperature of the equipment (this is a more logical place for the event than the Controller class is):

class TemperatureMonitor

{

public delegate void StopMachineryDelegate();

...

}

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