码迷,mamicode.com
首页 > 其他好文 > 详细

委托事件

时间:2016-04-07 01:07:15      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

class PubEventArgs : EventArgs
    {
        private readonly string _magname;

        public string Magname
        {
            get { return _magname; }
        } 

        public PubEventArgs(string magname)
        {
            _magname = magname;
        }
    }
    class Event//创建事件类
    {
        public delegate void PubComputerEventHandle(object sender,PubEventArgs e);//声明委托
        public event PubComputerEventHandle PubComputer;//创建委托链,即事件
        public delegate void PubLifeEventHandle(object sender, PubEventArgs e);
        public event PubLifeEventHandle PubLife;
        public virtual void OnComputer(PubEventArgs e)
        {
            PubComputerEventHandle handle = PubComputer;
            if (handle != null)
            {
                handle(this,e);
            }
        }
        public virtual void OnLife(PubEventArgs e)
        {
            PubLifeEventHandle handle = PubLife;
            if (handle != null)
            {
                handle(this, e);
            }
        }
        public void IsComputer(string magname)//创建触发事件过程
        {
            Console.WriteLine("发行"+magname+"杂志");
            OnComputer(new PubEventArgs(magname));
        }
        public void IsLife(string magname)
        {
            Console.WriteLine("发行" + magname + "杂志");
            OnComputer(new PubEventArgs(magname));
        }
    }
    class Man//创建操作主体
    {
        public string name;
        public Man(string name)
        {
            this.name = name;
        }
        public void Order(object sender, PubEventArgs e)//在主体中创建被委托的函数
        {
            Console.WriteLine(name + "订阅" + e.Magname + "刊物");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Event e = new Event();//事件建好
            Man zs = new Man("张三");//主体建好
            e.PubComputer += new Event.PubComputerEventHandle(zs.Order);//调用主体的被委托函数
            Man ls = new Man("李四");
            e.PubComputer += new Event.PubComputerEventHandle(ls.Order);
            e.PubLife += new Event.PubLifeEventHandle(ls.Order);
            e.IsComputer("电脑");//触发事件
            e.IsLife("生活");
            Console.Read();
        }
    }

 

委托事件

标签:

原文地址:http://www.cnblogs.com/liujianshe1990-/p/5361881.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!