using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace EventSamle{ public class AlarmEventArgs : System.EventArgs//事件参数 { private bool _snoozPresed;//懒惰键 private int _nrings;//响了几次 public bool SnoozPressed { get { return _snoozPresed; } set { _snoozPresed = value; } } public int NumRings { get { return _nrings; } set { _nrings = value; } } public string AlarmText//提醒 { get { if (SnoozPressed) return ("Wake up!!! snooze time is over."); else return ("Wake up!!!"); } } public AlarmEventArgs(bool snooz, int nrings) { this._snoozPresed = snooz; this._nrings = nrings; } } public delegate void AlarmEventHander(object sender, AlarmEventArgs e);//1.声明委托事件处理函数,其实是个类 public class AlarmClock//产生事件的类 { private bool _snoozPressed = false; private int _nrings = 0; private bool _stop = false; public bool Stop//是否停止。事件类的域,这个例子中事件处理函数会反馈修改这个域的值 { get { return _stop; } set { _stop = value; } } public bool SnoozPressed//是否懒惰。事件类的域,这个例子中事件处理函数会反馈修改这个域的值 { get { return _snoozPressed; } set { _snoozPressed = value; } } public event AlarmEventHander Alarm;//2.声明一个事件,或叫做产生一个委托事件处理函数的实例 protected virtual void OnAlarm(AlarmEventArgs e)//3.触发事件的函数,protected { if (Alarm != null)//一定要加! { Alarm(this, e); } } public void Start()//调用这个函数后开始触发事件,传入参数 { for (; ; ) { _nrings++; if (Stop) break; else if (SnoozPressed) { System.Threading.Thread.Sleep(1000); AlarmEventArgs e = new AlarmEventArgs(SnoozPressed, _nrings); OnAlarm(e); } else { System.Threading.Thread.Sleep(300); AlarmEventArgs e = new AlarmEventArgs(SnoozPressed, _nrings); OnAlarm(e); } } } } public class WakeUp//处理事件的类 { public void RingRang(object sender, AlarmEventArgs e)//4.处理事件的函数,同delegate签名一样 { Console.WriteLine(e.AlarmText+"\n"); if(!e.SnoozPressed) { Console.WriteLine(" Let alarm ring? Enter Y"); Console.WriteLine(" Stop Alarm? Enter Q"); Console.WriteLine(" Press Snooze? Enter N"); string input = Console.ReadLine(); if(input.Equals("Y")||input.Equals("y")) return; else if(input.Equals("Q")||input.Equals("q")) { ((AlarmClock)sender).Stop = true;//这个例子中可以向发送者反馈信息 return; } else { ((AlarmClock)sender).SnoozPressed = true; return; } } else { Console.WriteLine(" Let alarm ring? Enter Y"); Console.WriteLine(" Stop Alarm? Enter Q"); string input = Console.ReadLine(); if(input.Equals("Y")||input.Equals("y")) return; if(input.Equals("Q")||input.Equals("q")) { ((AlarmClock)sender).Stop = true; return; } } } } public class AlarmDriver//测试类 { public static void Main (string[] args) { // Instantiates the event receiver. WakeUp w= new WakeUp(); // Instantiates the event source. AlarmClock clock = new AlarmClock(); // Wires the AlarmRang method to the Alarm event. clock.Alarm += new AlarmEventHander(w.RingRang);//把事件处理函数注册到事件处理队列中 clock.Start(); } } }