4.事件篇

namespace ConsoleApplication2
{
    class Program
    {
        private static void student_registerFinish()
        {
            Console.WriteLine("注册成功");
        }
        static void Main(string[] args)
        {
            string stuName = Console.ReadLine();
            Student stu = new Student(stuName);
            //订阅student类的RegisterFinish
            stu.RegisterFinish += new Student.DelegateRegisterFinishEventHandler(student_registerFinish);
            stu.Register();//事件发生时通知事件订阅者
        }
    }
    class Student
    {
        public delegate void DelegateRegisterFinishEventHandler();//定义委托
        public event DelegateRegisterFinishEventHandler RegisterFinish; //通过委托定义事件
        private string name;
        public Student(string name)
        {
            this.name = name;
        }
        public void Register()
        {
            Console.WriteLine("学生{0}进行注册",name);
            if (RegisterFinish != null)
            {
                RegisterFinish();//引发事件
            }
        }
    }
}

 

1.事件与委托的关系

事件是特殊化的委托,委托是事件的基础;

2.理解

事件是对象发送的消息,发送信号通知客户发生了操作。这个操作可能是由鼠标单击引起的,也可能是由某些其他的程序逻辑触发的。事件的发送方不需要知道那个对象或者方法接收它引发的事件,发送方只需知道在它和接收方之间存在的中介(Deletgate)

3.定义事件
//定义事件之前需要定义委托
public delegate void DelegateEventHandler();
//定义一个事件
private event DelegateEventHandler EventMe;

4.订阅事件   指是为了添加一个委托,事件引发时该委托将调用一个方法。事件存在时为对象订阅事件。

EventMe += new DelegateEventHandler(//需要引用的方法); //该引用的方法就是订阅了该事件

5.引发事件 指要通知订阅某个事件的所有对象,需要引发该事件。引发事件与调用方法相似。

EventMe();  //引发该事件

6.特点

a.一个事件可以订阅多个订阅者。
b.发行者确定何时引发事件,订阅者确定执行何种操作来响应该事件
c.没有订阅者事件永远都不会被调用
d.事件通常用于通知操作

 

posted @ 2014-12-15 23:38  cygnet  阅读(139)  评论(0编辑  收藏  举报