1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Raising an Event ppt

1 263 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1
Dung lượng 7,59 KB

Nội dung

Raising an Event An event can be raised, just like a delegate, by calling it like a method. When you raise an event, all the attached delegates are called in sequence. For example, here's the TemperatureMonitor class with a private Notify method that raises the MachineryOverheating event: class TemperatureMonitor { public delegate void StopMachinerDelegate; public event StopMachineryDelegate MachineOverheating; private void Notify() { if (this.MachineOverheating != null) { this.MachineOverheating(); } } } This is a common idiom. The null check is necessary because an event field is implicitly null and only becomes non-null when a method subscribes to it by using the += operator. If you try and raise a null event, you will get a NullReferenceException. If the delegate defining the event expects any parameters, the appropriate arguments must be provided when you raise the event. You will see some examples of this later. IMPORTANT Events have a very useful built-in security feature. A public event (such as MachineOverheating) can only be raised by methods within the class that define it (the TemperatureMonitor class). Any attempt to raise the method outside of the class will result in a compiler error. . Raising an Event An event can be raised, just like a delegate, by calling it like a method. When you raise an event, all the attached. because an event field is implicitly null and only becomes non-null when a method subscribes to it by using the += operator. If you try and raise a null event,

Ngày đăng: 21/01/2014, 15:20

w