C#中引发和使用事件

 
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();
      }
   }  
}
 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值