1. 程式人生 > >C#中的委托和事件

C#中的委托和事件

方式 和我 col people += oev static .sh console

C#中的委托是一種類型,是方法的一種抽象,事件是一種特殊的委托。

區別在於:委托可以直接賦值和調用,而事件只能在外部進行賦值和調用,事件在外部只能用+=進行訂閱。

委托的幾種調用方式:

NoReturnWithPara method = new NoReturnWithPara(ShowPlus); //實例化委托

// method(3,4);

//method.Invoke(3,4);

//method.BeginInvoke(3,4,null,null); //異步調用

多播委托是不能異步調用的,多播委托用+=,-=去添加和移除多個方法,但是lambda表達式(匿名方法)是移除不了的。

多播委托帶返回值,結果是最後那個方法的。

  public class MyDelegate
    {
        public delegate void NoReturnNoPara();
        public delegate void NoReturnWithPara(int x,int y);   //聲明委托

        public void Show()
        {
            NoReturnWithPara method = new NoReturnWithPara(ShowPlus);  //實例化委托
           
// method(3,4); //method.Invoke(3,4); //ShowPlus(3,4); //method.BeginInvoke(3,4,null,null); //異步調用 //多播委托 method += ShowPlus; method += (x, y) => Console.WriteLine("我是{0}和我得啥{1}",x,y); method += ShowPlusStatic; method
+= ShowPlusStatic; method += ShowPlusStatic; method -= ShowPlus; method -= ShowPlusStatic; //lambda表達式(匿名方法)是無法移除的。 method -= (x, y) => Console.WriteLine("我是{0}和我得啥{1}", x, y); method(7,8); // method.BeginInvoke(7,8,null,null); //多播委托是不能異步的 Func<string, int> func = s => s.Length; func += s => s.Length + 2; func += s => s.Length + 3; func += s => s.Length + 1; int iResult = func("Zain"); //5 多播委托帶返回值,結果是最後那個方法的。 } public void ShowPlus(int x,int y) { Console.WriteLine("打印x,和y的值{0},{1}",x,y); } public static void ShowPlusStatic(int x, int y) { Console.WriteLine("static打印x,和y的值{0},{1}", x, y); } }

委托和事件的區別,發布訂閱模式(觀察者模式),貓叫,老鼠跑,小孩哭,大人醒。

  /// <summary>
  /// 發布者    (發布訂閱模式,觀察者模式。)
  /// </summary>
    public class Cat
    {
        public Action CatMiaoHandler;
        public event Action CatMiaoHandlerEvent;  //事件就是委托的一個實例,加上event關鍵字修飾
        public void Miao()
        {
            Console.WriteLine("{0} Miao", this.GetType().Name);

        

            new Neighbor().Awake();
            new Mouse().Run();
            new Dog().Wang();
            new Baby().Cry();
            new Father().Shout();
            new Mother().Whiper();

        }

        public void MiaoDelegate()
        {
            Console.WriteLine("{0} Miao", this.GetType().Name);

            if (CatMiaoHandler != null)
            {
                CatMiaoHandler();
            }

        }

        public void MiaoEvent()
        {
            Console.WriteLine("{0} Miao", this.GetType().Name);

            if (CatMiaoHandlerEvent != null)
            {
                CatMiaoHandlerEvent.Invoke();
            }
            CatMiaoHandlerEvent = null;               //事件內部可以賦值,可以調用

        }
    }
  class Program
    {
       
         
        static void Main(string[] args)
        {
            MyDelegate md = new MyDelegate();
            md.Show();

            Greeting greeting = new Greeting();
            //greeting.SayHi("zain",Greeting.PeopleType.Chinese);

            //greeting.SayHi("Eleven", Greeting.PeopleType.Buluo);



            Action<string> act = new Action<string>(greeting.SayHiChinese);
            greeting.SayHiDelegate("zain",act);





            {

                Cat cat = new Cat();
                cat.Miao();

                Console.WriteLine("******************************Delegate****************");
                cat.CatMiaoHandler = () => Console.WriteLine("這裏是Delegate");  //直接給委托賦值
                cat.CatMiaoHandler += new Neighbor().Awake;
                cat.CatMiaoHandler += new Mouse().Run;
                cat.CatMiaoHandler += new Dog().Wang;
                cat.CatMiaoHandler += new Baby().Cry;
                cat.CatMiaoHandler += new Father().Shout;
                cat.CatMiaoHandler += new Mother().Whiper;

                cat.CatMiaoHandler.Invoke();    //直接調用委托
                cat.MiaoDelegate();
            }
            {

                Cat cat = new Cat();
                cat.Miao();

                Console.WriteLine("******************************Event****************");
          //      cat.CatMiaoHandlerEvent = () => Console.WriteLine("這裏是Event");  //外部不能直接給事件賦值
                cat.CatMiaoHandlerEvent += new Neighbor().Awake;    //事件的訂閱
                cat.CatMiaoHandlerEvent += new Mouse().Run;
                cat.CatMiaoHandlerEvent += new Dog().Wang;
                cat.CatMiaoHandlerEvent += new Baby().Cry;
                cat.CatMiaoHandlerEvent += new Father().Shout;
                cat.CatMiaoHandlerEvent += new Mother().Whiper;

           //     cat.CatMiaoHandlerEvent()   //外部不能直接調用事件
                cat.MiaoEvent();
            }





            Console.ReadKey();
        }



     
    }


C#中的委托和事件