其他分享
首页 > 其他分享> > 多播委托

多播委托

作者:互联网

简介

代码实现

 	//声明委托
    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

标签:多播,Console,委托,Action,WriteLine,action,MethodTest
来源: https://www.cnblogs.com/wml-it/p/16070173.html