Program.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ConsoleEventDelegate
  7. {
  8. internal class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. SchoolRing sr = new SchoolRing();//创建学校铃声类
  13. Students student = new Students();//创建学生实例
  14. student.SubscribeToRing(sr);//订阅铃声
  15. Console.Write("请输入打铃参数(1:表示打上课铃;2:表示打下课铃):");
  16. sr.Jow(Convert.ToInt32(Console.ReadLine()));//打铃动作
  17. Console.ReadLine();
  18. }
  19. }
  20. //第一步:声明一个委托类型,参数ringKind表示铃声种类(1:表示上课铃声;2表示下课铃声)
  21. public delegate void RingEvent(int ringKind);
  22. //第二步
  23. public class SchoolRing
  24. {
  25. public RingEvent OnBellSound; //委托发布
  26. public void Jow(int ringKind) //打铃
  27. {
  28. if (ringKind == 1 || ringKind == 2)
  29. {
  30. Console.Write(ringKind == 1 ? "上课铃声响了," : "下课铃声响了,");
  31. if (OnBellSound != null)//不等于空,说明它已经订阅了具体的方法(即它已经引用了具体的方法)
  32. {
  33. OnBellSound(ringKind);//回调OnBellSound委托所订阅(或引用)的具体方法
  34. }
  35. }
  36. else
  37. {
  38. Console.WriteLine("这个铃声参数不正确!");
  39. }
  40. }
  41. }
  42. public class Students
  43. {
  44. //学生们订阅铃声这个委托事件
  45. public void SubscribeToRing(SchoolRing schoolRing)
  46. {
  47. schoolRing.OnBellSound += SchoolJow;
  48. }
  49. //定义铃声事件的处理方法
  50. public void SchoolJow(int ringKind)
  51. {
  52. if (ringKind == 2)//打了下课铃
  53. {
  54. Console.WriteLine("同学们开始课间休息!");
  55. }
  56. else if (ringKind == 1)//打了上课铃
  57. {
  58. Console.WriteLine("同学们开始认真学习!");
  59. }
  60. }
  61. public void CancelSubscribe(SchoolRing schoolRing)//取消订阅铃声动作
  62. {
  63. schoolRing.OnBellSound -= SchoolJow;
  64. }
  65. }
  66. }