事件和委托解析

事件(Event)
 
对象将处于什么样的的场景,然后在该场景下会触发什么样的动作
 
委托(Delegate)
 
1. 委托的本质是类,类似函数指针,可以降低耦合性,提高安全性
2. 可以实现多线程,异步调用,回调函数等
3. 委托可以调用静态或非静态的函数,使得可以的统一标准
4. 多播委托(委托链)
 
代码:
public delegate void WolfShoutEventHandler();  //定义委托
 
public event WolfShoutEventHandler WolfShout;//定义事件
 
注:当WolfShout事件触发时执行WolfShoutEventHandler委托的方法
 
场景模拟:灰太狼只要叫一声“哈,我是灰太狼”,喜羊羊和懒羊羊就说“不好,狼来了,快跑!
 
class Wolf
    {
        private string _name;
 
        public Wolf(string name)
        {
            this._name = name;
        }
 
        public delegate void WolfShoutEventHandler();   //定义委托
        public event WolfShoutEventHandler WolfShout;  //定义事件
 
      // 事件触发的方法
        public void Shout()
        {
            Console.WriteLine("哈,我是{0}。", this._name);
            if (WolfShout != null)  //判断事件是否被绑定
            {
                WolfShout();  //触发事件
            }
        }
    }
class Goat
    {
        private string _name;
 
        public Goat(string name)
        {
            this._name = name;
        }
 
        public void Run() 
        {
            Console.WriteLine("狼来了,{0}快跑!",this._name);
        }       
    }
class Program
    {
        static void Main(string[] args)
        {
            Wolf grayWolf = new Wolf("灰太狼");
 
            Goat happyGoat = new Goat("喜羊羊");
            Goat fattyGoat = new Goat("懒羊羊");
            Goat forceGoat = new Goat("沸羊羊");
 
             //关联狼的叫方法和羊跑的方法(多播委托/委托链)
            grayWolf.WolfShout += new Wolf.WolfShoutEventHandler(happyGoat.Run)
                                                 + new Wolf.WolfShoutEventHandler(fattyGoat.Run)
                                                 + new Wolf.WolfShoutEventHandler(forceGoat.Run);
            grayWolf.Shout();  // 触发事件
            Console.ReadLine();    
        }
    }

 

 
 

public event WolfShoutEventHandler WolfShout;定义事件

posted @ 2017-08-27 09:28  oliverary  阅读(154)  评论(0编辑  收藏  举报