在C#中事件其实是一个委托类型的变量,可以用EventHandler委托类型声明一个标准的事件,也可以自定义委托,再声明自定义事件。事件和委托是分不开的。如果web开发中不用事件驱动,那服务器如何与用户实现交互?
用事件驱动模型来解决新生报到注册的问题,代码如下:- class Program
- {
- class Student
- {
- public string name;
- public char sex;
- public Student(string name, char sex)
- {
- this.name = name;
- this.sex = sex;
- }
- }
- //新生注册事件参数类
- class StudentEventArgs : EventArgs
- {
- private Student someone;
- public StudentEventArgs(Student s)
- {
- someone = s;
- }
- public Student student
- {
- get { return someone; }
- }
- }
- class Grade //班级类,也是事件的发送者
- {
- private ArrayList list; //声明列表,用来保持本班已报到的学生信息
- //声明新生报到的委托类型
- public delegate void StudentHandler(Object sender, StudentEventArgs g);
- public event StudentHandler onNewStudent; //声明新生注册事件
- public Grade()
- {
- list = new ArrayList();
- }
- //新生s在班级名单上登记报到
- public void Add(Student s)
- {
- list.Add(s);
- }
- //注册学校花名册,同时发布事件
- public void ProcessRegister()
- {
- Student s;
- for (int i = 0; i < list.Count; i++)
- {
- s = (Student)list[i];
- StudentEventArgs e = new StudentEventArgs(s);
- if (onNewStudent != null && s != null)
- onNewStudent(this, e); //触发事件,发送学生信息
- }
- }
- }
- class School
- {
- private int students; //声明全校学生人数
- private ArrayList list;
- public School()
- {
- students = 0;
- list = new ArrayList();
- }
- //声明索引器
- public Student this[int index]
- {
- get
- {
- if (index < 0 || index >= list.Count)
- return (Student)list[0];
- else
- return (Student)list[index];
- }
- }
- public int Count //返回全校学生人数
- {
- get { return students; }
- }
- //声明事件函数,将学生s注册到学校的花名册上
- private void Add_NewStudent(object sender, StudentEventArgs e)
- {
- if (e.student != null)
- {
- students++;
- list.Add(e.student);
- }
- }
- public void AddStudents(Grade g) //声明一个订阅新生注册事件的方法
- {
- //绑定事件与事件处理函数
- g.onNewStudent += new Grade.StudentHandler(this.Add_NewStudent);
- }
- }
- static void Main(string[] args)
- {
- Grade g = new Grade();
- School school = new School();
- Student s = new Student("敌法师", '男');
- g.Add(s);
- s = new Student("屠夫", '男');
- g.Add(s);
- s = new Student("秀逗魔法师", '女');
- g.Add(s);
- school.AddStudents(g);
- g.ProcessRegister(); //以班级为单位进行学生注册,注册时发布时间
- Console.WriteLine("全校已注册的学生共计{0}人,详细名单如下:", school.Count);
- for (int i = 0; i < school.Count; i++)
- {
- Console.WriteLine("姓名:{0}\t性别:{1}", school[i].name, school[i].sex);
- }
- }
复制代码 |