Program.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. namespace EventDemo1
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Console.WriteLine("Hello World!");
  9. EventTest e = new EventTest(); /* 实例化对象,第一次没有触发事件 */
  10. subscribEvent v = new subscribEvent(); /* 实例化对象 */
  11. e.ChangeNum += new EventTest.NumManipulationHandler(v.printf); /* 注册 */
  12. e.SetValue(7);
  13. e.SetValue(11);
  14. }
  15. }
  16. /***********发布器类***********/
  17. public class EventTest
  18. {
  19. private int value;
  20. public delegate void NumManipulationHandler( int a );
  21. public event NumManipulationHandler ChangeNum;
  22. protected virtual void OnNumChanged(int a)
  23. {
  24. if (ChangeNum != null)
  25. {
  26. ChangeNum(a); /* 事件被触发 */
  27. }
  28. else
  29. {
  30. Console.WriteLine("event not fire");
  31. Console.ReadKey(); /* 回车继续 */
  32. }
  33. }
  34. public EventTest()
  35. {
  36. int n = 5;
  37. SetValue(n);
  38. }
  39. public void SetValue(int n)
  40. {
  41. if (value != n)
  42. {
  43. value = n;
  44. OnNumChanged(n);
  45. }
  46. }
  47. }
  48. /***********订阅器类***********/
  49. public class subscribEvent
  50. {
  51. public void printf(int a )
  52. {
  53. Console.WriteLine(a+"event fire");
  54. Console.ReadKey(); /* 回车继续 */
  55. }
  56. }
  57. }