C#委托与事件

 

委托与事件
class MyEventArgs : EventArgs
    {
        private int _light;
        public MyEventArgs(int light)
        {
            _light = light;
        }
        public int Light
        {
            get 
            {
                return _light;
            }
        }
    }
    class LightSender
    {
        //声明委托
        public delegate void LightEventHander(object sender, MyEventArgs e);
        //声明开灯事件
        public event LightEventHander LightEvent;
        //声明关灯事件
        public event LightEventHander CloseEvent;
        public void OnLightEvent()
        {
            //判断发送者是否为null
            LightEventHander hander = LightEvent;
            if (hander != null)
            {
                bool judge = true;
                while (judge)
                {
                    Console.WriteLine("请输入当前亮度:");
                    int light = Convert.ToInt32(Console.ReadLine());
                    MyEventArgs e = new MyEventArgs(light);
                    if (e.Light < 30)
                    {
                        LightEvent(this, e);//触发开灯事件
                    }
                    if (e.Light == 30)
                    {
                        CloseEvent(this, e);//触发关灯事件
                    }
                }
                
            }
        }
    }
    class Program
    {
        public Program()
        {
            LightSender ls = new LightSender();
            //绑定LightEvent事件
            ls.LightEvent += new LightSender.LightEventHander(ls_LightEvent);
            //绑定CloseEvent事件
            ls.CloseEvent += new LightSender.LightEventHander(ls_CloseEvent);
            ls.OnLightEvent();
        }
        static void Main(string[] args)
        {
            Program p = new Program();
        }
        /// <summary>
        /// 关闭事件处理程序
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件状态</param>
        static void ls_CloseEvent(object sender, MyEventArgs e)
        {
            Console.WriteLine("CloseEvent事件响应:天明了——关灯");
        }
        /// <summary>
        /// 开灯时间处理程序
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件状态</param>
        static void ls_LightEvent(object sender, MyEventArgs e)
        {
            Console.WriteLine("LightEvent事件响应:天已黑——开灯");
        }
    }

 注:代码来自网络!!!

posted on 2012-07-23 10:55  YuanSong  阅读(514)  评论(0编辑  收藏  举报

导航