• 事件的拥有者(event source)
    • 事件成员(event)
    • 事件的响应者(event subscriber)
    • 事件处理器(event handler)
    • 事件订阅

      1. //事件发送者
      2. class Dog
      3. {
      4. //1.声明关于事件的委托;
      5. public delegate void AlarmEventHandler(object sender, EventArgs e);
      6. //2.声明事件;
      7. public event AlarmEventHandler Alarm;
      8. //3.编写引发事件的函数;
      9. public void OnAlarm()
      10. {
      11. if (this.Alarm != null)
      12. {
      13. Console.WriteLine("\n狗报警: 有小偷进来了,汪汪~~~~~~~");
      14. this.Alarm(this, new EventArgs()); //发出警报
      15. }
      16. }
      17. }
      18. //事件接收者
      19. class Host
      20. {
      21. //4.编写事件处理程序
      22. void HostHandleAlarm(object sender, EventArgs e)
      23. {
      24. Console.WriteLine("主人: 抓住了小偷!");
      25. }
      26. //5.注册事件处理程序
      27. public Host(Dog dog)
      28. {
      29. dog.Alarm += new Dog.AlarmEventHandler(HostHandleAlarm);
      30. }
      31. }
      32. //6.现在来触发事件
      33. class Program
      34. {
      35. static void Main(string[] args)
      36. {
      37. Dog dog = new Dog();
      38. Host host = new Host(dog);
      39. //当前时间,从2008年12月31日23:59:50开始计时
      40. DateTime now = new DateTime(2015, 12, 31, 23, 59, 50);
      41. DateTime midnight = new DateTime(2016, 1, 1, 0, 0, 0);
      42. //等待午夜的到来
      43. Console.WriteLine("时间一秒一秒地流逝... ");
      44. while (now < midnight)
      45. {
      46. Console.WriteLine("当前时间: " + now);
      47. System.Threading.Thread.Sleep(1000); //程序暂停一秒
      48. now = now.AddSeconds(1); //时间增加一秒
      49. }
      50. //午夜零点小偷到达,看门狗引发Alarm事件
      51. Console.WriteLine("\n月黑风高的午夜: " + now);
      52. Console.WriteLine("小偷悄悄地摸进了主人的屋内... ");
      53. dog.OnAlarm();
      54. Console.ReadLine();
      55. }
      56. }