1. 程式人生 > 其它 >多播委託

多播委託

簡介

  • 每一個委託都是繼承自MulticastDelegate,也就是每個都是多播委託。
  • 帶返回值的多播委託只返回最後一個方法的值
  • 多播委託可以用加減號來操作方法的增加或者減少。
  • 給委託傳遞相同方法時 生成的委託例項也是相同的(也就是同一個委託)

程式碼實現

 	//宣告委託
    delegate void MulticastTest();
    public class MulticastDelegateTest
    {
        
            
        public void Show()
        {
            MulticastTest multicastTest = new MulticastTest(MethodTest);
            multicastTest();



            Action action =new Action(MethodTest);
            action = (Action)MulticastDelegate.Combine(action, new Action(MethodTest2));
            action = (Action)MulticastDelegate.Combine(action, new Action(MethodTest3));
            action = (Action)MulticastDelegate.Remove(action, new Action(MethodTest3));
            action();

            //等同於上面
            action = MethodTest;
            action += MethodTest2;
            action += MethodTest3;
            action -= MethodTest3;

            foreach (Action action1 in action.GetInvocationList())
            {
                action1();
            }
            Console.WriteLine("==========");
            action();
                        


            Func<string> func = () => { return "我是Lambda"; };
            func += () => { return "我是func1"; };
            func += () => { return "我是func2"; };
            func += GetTest;
            func += GetTest; //給委託傳遞相同方法時 生成的委託例項也是相同的(也就是同一個委託)
            
            string result = func();
            Console.WriteLine(result);
            Console.WriteLine("==========");
        }


        #region 委託方法
        public void MethodTest()
        {
            Console.WriteLine("我是方法MethodTest()1");
        }

        public void MethodTest2()
        {
            Console.WriteLine("我是方法MethodTest()2");
        }

        public void MethodTest3()
        {
            Console.WriteLine("我是方法MethodTest()3");
        }

        public string GetTest()
        {
            return "我是方法GetTest()";
        }
        #endregion