C#中引发和使用事件
下面的示例程序阐释如何在一个类中引发一个事件,然后在另一个类中处理该事件。
AlarmClock
类定义公共事件
Alarm
,并提供引发该事件的方法。
AlarmEventArgs
类派生自
EventArgs
,并定义
Alarm
事件特定的数据。
WakeMeUp
类定义处理
Alarm
事件的
AlarmRang
方法。
AlarmDriver
类一起使用类,将使用
WakeMeUp
的
AlarmRang
方法设置为处理
AlarmClock
的
Alarm
事件。
namespace EventSample
{
using System;
using System.ComponentModel;
//步驟1.先定義一個自已的事件參數,如果只使用已有的參數,這一步可省略.
// Class that contains the data for
// the alarm event. Derives from System.EventArgs.
public class AlarmEventArgs : EventArgs
{
public AlarmEventArgs(bool snoozePressed, int nrings)
{ }
}
//步驟2.聲明一個委托
// Delegate declaration.
public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);
// The Alarm class that raises the alarm event.
public class AlarmClock
{
//步驟3.聲明一個事件
// The event member that is of type AlarmEventHandler.
public event AlarmEventHandler Alarm;
//步驟4.定義一個調用該事件的方法
// The protected OnAlarm method raises the event by invoking
// the delegates. The sender is always this, the current instance of the class.
protected virtual void OnAlarm(AlarmEventArgs e)
{
AlarmEventHandler handler = Alarm;
if (handler != null)
{
// Invokes the delegates.
handler(this, e);
}
}
//步驟5.在本類的方法中調用事件
// This alarm clock does not have a user interface.
public void Start()
{
AlarmEventArgs e = new AlarmEventArgs(snoozePressed, nrings);
OnAlarm(e);
}
}
//步驟5.在事件中調用其它類中的方法(該方法与委托具有相同的格式)
// The WakeMeUp class has a method AlarmRang that handles the alarm event.
public class WakeMeUp
{
//在其它類中定義与委托有相同格式的方法
public void AlarmRang(object sender, AlarmEventArgs e)
{ }
}
// The driver class that hooks up the event handling method of
// WakeMeUp to the alarm event of an Alarm object using a delegate.
// In a forms-based application, the driver class is the form.
public class AlarmDriver
{
public static void Main (string[] args)
{
// Instantiates the event receiver.
WakeMeUp w= new WakeMeUp();
// Instantiates the event source.
AlarmClock clock = new AlarmClock();
//在事件中調用其它類中的方法(該方法与委托具有相同的格式)
// Wires the AlarmRang method to the Alarm event.
clock.Alarm += new AlarmEventHandler(w.AlarmRang);
clock.Start();
}
}
}