C#学习:事件
类或对象可以通过事件向其他类或对象通知发生的相关事情。 发送(或引发)事件的类称为“发行者”,接收(或处理)事件的类称为“订阅者”。
- 一个简单事件实例
//发行者 public class Student { private string name; //定义一个带参委托 public delegate void DelegateRegisterFinish(string name); //定义一个事件 public event DelegateRegisterFinish EventRegisterFinish; public Student(string name) { this.name = name; } //在一定条件下,发行者发布事件 public void Register() { Console.WriteLine("学生{0}进行注册", name); if (EventRegisterFinish != null) EventRegisterFinish(name); } }
//订阅者 class RegisterStudent { static void Main(string[] args) { Console.WriteLine("输入学生姓名:"); string studentName = Console.ReadLine(); Console.WriteLine("--------------------------------------"); Student student = new Student(studentName); //为静态方法student_EventRegisterFinishOne订阅事件 //C#1.0语法 student.EventRegisterFinish += new Student.DelegateRegisterFinish(student_EventRegisterFinishOne); //C#2.0语法 //student.EventRegisterFinish += student_EventRegisterFinishOne; //为RegisterStudent实例对象的student_EventRegisterFinishTwo方法订阅事件 //本处其实利用多路广播委托为多个方法订阅事件 RegisterStudent rs = new RegisterStudent(); student.EventRegisterFinish += rs .student_EventRegisterFinishTwo; //发行者发布事件后订阅者做相应的操作 student.Register(); Console.WriteLine("--------------------------------------"); //取消订阅 student.EventRegisterFinish -= rs .student_EventRegisterFinishTwo; student.Register(); Console.Read(); } private static void student_EventRegisterFinishOne(string name) { Console.WriteLine("{0}注册成功", name); } private void student_EventRegisterFinishTwo(string name) { Console.WriteLine("{0}请及时领取住宿用品", name); } }
结果: