Program.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. namespace EventDemo
  3. {
  4. public delegate void ProcessDelegate(object sender, EventArgs e);
  5. class Program
  6. {
  7. public event ProcessDelegate ProcessEvent;
  8. static void Main(string[] args)
  9. {
  10. // 方式1 委托方式创建事件
  11. Swim swim = new Swim();//实例化发布者
  12. MyClass myClass = new MyClass();//实例化订阅者
  13. myClass.EventABS += new MyClass.DelegateABS<string>(swim.You);//事件的固定格式 事件名+= new 委托(发布者的方法)
  14. myClass.OK("大家好!");
  15. // 方式2 EventArgs 创建
  16. /* 第一步执行 */
  17. Test t = new Test();
  18. /* 关联事件方法,相当于寻找到了委托人 */
  19. t.ProcessEvent += new ProcessDelegate(t_ProcessEvent);
  20. /* 进入Process方法 */
  21. Console.WriteLine(t.Process());
  22. //方式3
  23. //实例化发布者
  24. MailManager mm = new MailManager();
  25. //向事件登记回调方法
  26. Fax f = new Fax(mm);
  27. mm.SimulateNewMail("a", "b", "Hello World!");
  28. Console.ReadKey();
  29. }
  30. static void t_ProcessEvent(object sender, EventArgs e)
  31. {
  32. Test t = (Test)sender;
  33. t.Text1 = "Hello";
  34. t.Text2 = "World";
  35. }
  36. }
  37. public class Test {
  38. public string Text1 { get; set; }
  39. public string Text2 { get; set; }
  40. public event ProcessDelegate ProcessEvent;
  41. void ProcessAction(object sender, EventArgs e)
  42. {
  43. //if (ProcessEvent == null)
  44. // ProcessEvent += new ProcessDelegate(t_ProcessEvent);
  45. ProcessEvent(sender, e);
  46. }
  47. //如果没有自己指定关联方法,将会调用该方法抛出错误
  48. //void t_ProcessEvent(object sender, EventArgs e)
  49. //{
  50. // throw new Exception("The method or operation is not implemented.");
  51. //}
  52. void OnProcess()
  53. {
  54. ProcessAction(this, EventArgs.Empty);
  55. }
  56. public string Process()
  57. {
  58. OnProcess();
  59. return Text1 + Text2;
  60. }
  61. }
  62. class MyClass //定一个订阅者的类
  63. {
  64. //定义一个委托
  65. public delegate void DelegateABS<T >(T a);
  66. //定义一个事件
  67. public event DelegateABS<string > EventABS;
  68. //定义一个方法
  69. public void OK(string a )
  70. {
  71. EventABS(a);//调用事件
  72. }
  73. }
  74. class Swim//定义一个发布者
  75. {
  76. public void You(string a )
  77. {
  78. Console.WriteLine(a+"我喜欢游泳");
  79. }
  80. }
  81. }