Declaring an Event

Chia sẻ: Nghia Tuan | Ngày: | Loại File: PDF | Số trang:2

lượt xem

Declaring an Event

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tuyên bố một sự kiện Bạn tuyên bố một sự kiện trong một lớp học dự định để hoạt động như một nguồn sự kiện. Một nguồn sự kiện thường là một lớp học mà giám sát môi trường của nó, và đặt ra một sự kiện quan trọng xảy ra khi một cái gì đó. Trong các nhà máy tự động

Chủ đề:

Nội dung Text: Declaring an Event

  1. 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 monitor class would raise a “machine overheating” event if it detects that a machine has exceeded its thermal radiation boundary (i.e. 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 the machines down. You declare an event in a way similar to declaring a field. However, because events are intended be used with delegates, the type of an event must be a delegate, and you must prefix the declaration with the event keyword. For example, here's the StopMachineryDelegate delegate from the automated factory. I have relocated it to a new class called TemperatureMonitor, which provides an interface to the various electonic probes monitoring the temperature of the equipment (this is a more logical place for the event than the Controller class): class TemperatureMonitor { public delegate void StopMachineryDelegate(); ... } You can define the MachineOverheating event, which will invoke the stopMachineryDelegate, like this: class TemperatureMonitor { public delegate void StopMachineryDelegate(); public event StopMachineryDelegate MachineOverheating; ... } The logic (not shown) in the TemperatureMonitor class automatically raises the MachineOverheating event as necessary. An event maintains its own internal collection of attached delegates, so there is no need to manually maintain your delegate variable.
Đồng bộ tài khoản