⑤手写标准事件
1 public class CustomEvent 2 { 3 public static void show() { 4 student s = new student() 5 { 6 id = 99, 7 Name = "小明" 8 }; 9 Console.WriteLine($"{s.Name}的作业数量{s.HomeWorkCount}"); 10 s.studentHomeWorkToomuch += new TeacherInfo().addHomeWork; 11 s.studentHomeWorkToomuch += new StudentInfo().doHomeWork; 12 s.HomeWorkCount = 5; 13 Console.WriteLine($"{s.Name}的作业数量{s.HomeWorkCount}"); 14 15 16 17 } 18 /// <summary> 19 /// 订户:关注事件,事件触发后,自己做出相应的动作 20 /// </summary> 21 public class StudentInfo { 22 public void doHomeWork(object s,EventArgs e) { 23 Console.WriteLine("***********学生的反应********************"); 24 student stu = (student)s; 25 HomeWorkEventArgs homeWorkEventArgs = (HomeWorkEventArgs)e; 26 Console.WriteLine($"学生姓名:{stu.Name}"); 27 Console.WriteLine($"学生作业完成数量:{homeWorkEventArgs.finishedCont}"); 28 Console.WriteLine($"学生未完成作业数量:{homeWorkEventArgs.WillfinishCont}"); 29 Console.WriteLine($"{stu.Name} : 老师你睡了吗?!"); 30 Console.WriteLine("*******************************"); 31 32 } 33 } 34 /// <summary> 35 /// 订户:关注事件,事件触发后,自己做出相应的动作 36 /// </summary> 37 public class TeacherInfo 38 { 39 public void addHomeWork(object s, EventArgs e) 40 { 41 Console.WriteLine("***********老师的反应********************"); 42 Console.WriteLine("没有写完,放学别走"); 43 Console.WriteLine("*******************************"); 44 45 } 46 } 47 /// <summary> 48 /// 事件的发布者者,发布是按在满足的情况下,触发事件 49 /// </summary> 50 public class student 51 { 52 public int id { get; set; } 53 public string Name { get; set; } 54 55 private int _homeWorkCount=2;//可以完成数量 56 57 public int HomeWorkCount 58 { 59 get 60 { 61 return _homeWorkCount; 62 } 63 set 64 { 65 if (value > _homeWorkCount) 66 { 67 //触发 68 studentHomeWorkToomuch.Invoke(this, new HomeWorkEventArgs() 69 { 70 finishedCont = _homeWorkCount, 71 WillfinishCont = value - _homeWorkCount 72 });; 73 } 74 _homeWorkCount = value; 75 } 76 } 77 public event EventHandler studentHomeWorkToomuch; 78 } 79 public class HomeWorkEventArgs : EventArgs 80 { 81 public int finishedCont { get; set; } 82 public int WillfinishCont { get; set; } 83 } 84 85 86 }
//ps:不知道我有没有写清需求^_^