C Sharp 多播委托

版权声明:原创笔记 ----黑暗灵魂 https://blog.csdn.net/qq_38843118/article/details/89634233

        static void Action01() { Console.Write("1 "); }
        static void Action02() { Console.Write("2 "); }
        static void ActionX(int x) { Console.Write(x + " "); }

        static void Main(string[] args)
        {
            //多播委托
            Action a = null;
            a += Action01;
            a += Action02;
            a();    
            //输出 1 2
            Console.WriteLine("");
            
            a -= Action01;
            a();
            //输出 2
            Console.WriteLine("");

            a += () => ActionX(0);
            a();
            //输出 2 0
            Console.WriteLine("");
            
            a -= () => ActionX(0);
            a();
            //输出 2 0
            Console.WriteLine("");

            a += () => Console.Write("3 ");
            a();
            //输出 2 0 3
            Console.WriteLine("");
            
            a -= () => Console.WriteLine("3");
            a();
            //输出 2 0 3
            Console.WriteLine("");
            
            //获取多播委托中的每一个方法
            Delegate[] fun = a.GetInvocationList();
            //获取多播委托中的每一个方法
            for (int i = 0; i < fun.Length; i++)
            {
                Console.Write("第" + i + "个方法: ");
                fun[i].DynamicInvoke();     //可以传递参数
                Console.WriteLine("");
            }
            Console.ReadKey();
        }

猜你喜欢

转载自blog.csdn.net/qq_38843118/article/details/89634233