C#事件的容易认识

C#事件的简单认识

 事件是C#的一个重要特性。事件主要涉及发布者,订阅者,以及事件处理程序。

 使用.net 类库中预定义的委托类型可以很方便的定义事件。    发布者触发事件后,订阅者即执行事件处理函数:代码及运行结果如下:

   

 public class Yiqiok            //事件发布者
    {
        public event EventHandler LolInvite;  //使用.NET类库预定义的委托类型定义事件
        public void InviteComing(string msg)  //发出事件
        {
            if(LolInvite!=null)   //检查是否添加了事件处理方法
            {
                Console.WriteLine(msg);
                LolInvite(this, new EventArgs());  //触发事件

            }
        }
        
    }
    public class Classmate  //事件订阅者
    {
        private string name;
        public Classmate (string Name)
        {
            name = Name;
        }
        public void SendResponse(object s,EventArgs e)  //事件处理函数,要与预定义委托类型匹配
        {
            Console.WriteLine("来自:" + this.name + "的回复: 已经收到邀请,随时可以开始!");
        }
    }
    public class Start
    {
        static void Main()
        {
            Yiqiok yiqiok = new Yiqiok();//初始化
            Classmate classmate1 = new Classmate("Lna");
            Classmate classmate2 = new Classmate("Jim");
            Classmate classmate3 = new Classmate("Cry");
            Classmate classmate4 = new Classmate("Tom");

            yiqiok.LolInvite += new EventHandler(classmate1.SendResponse);//订阅事件
            yiqiok.LolInvite += new EventHandler(classmate2.SendResponse);
            yiqiok.LolInvite += new EventHandler(classmate3.SendResponse);
            yiqiok.LolInvite += new EventHandler(classmate4.SendResponse);

            yiqiok.InviteComing("yiqiok:五人开黑来不来???");  //发出通知

        }
    }

C#事件的容易认识