zoukankan      html  css  js  c++  java
  • 多播委托

    多播委托就是一个委托同时绑定多个方法,多播委托也叫委托链,委托组合。

    无返回值的多播委托

       static void Main(string[] args)
            {
                //这句话绑定一个add1方法(绑定第一个方法不能用+=方式,因为my开始为null,所以只能用=赋值)
                Action my = add1;
                my += add2;
                my += add3;
                my += add4;
                my -= add2;//解绑add2方法。
                    
                my();
                Console.ReadKey();
            }
            static void add1()
            {
                Console.WriteLine("世界你好");
            }
            static void add2()
            {
                Console.WriteLine("世界你好");
            }
            static void add3()
            {
                Console.WriteLine("世界你好");
            }
            static void add4()
            {
                Console.WriteLine("世界你好");
            }

    有返回值的多播委托的时候只能得到最后一个方法的返回值。如果要获取前面方法的返回值,请参照下面

      static void Main(string[] args)
            {
                Func<string, string> my = add1;
                my += add2;
                my += add3;
                my += add4;
                string sum=my.Invoke("有返回值的多播委托");
                //按照调用循序返回此多路广播委托的调研列表,即是有几个方法就有几个委托,返回值为Delegate数组
                Delegate[] dele = my.GetInvocationList();
                //循环遍历Delegate数据即可得到每个委托对象,这样就可以逐个委托调用,如果有返回值,就可以逐个拿到
                for (int i = 0; i < dele.Length; i++)
                {
                    //这句不行,因为Delegate是抽象类,所以不能直接调用,需要强转为子类Func<string,string>
                    // dele[i]("SS");
                    string s = (dele[i] as Func<string, string>)("有返回值的多播委托");
                    Console.WriteLine(s);
                }
                
                Console.ReadKey();
            }
            static string add1(string a)
            {
                return a + "1";
            }
            static string add2(string a)
            {
                return a + "2";
            }
            static string add3(string a)
            {
                return a + "3";
            }
            static string add4(string a)
            {
                return a + "4";
            }
  • 相关阅读:
    普通平衡树(treap与splay模板)
    NOIP2009T4 靶形数独
    单调队列模板
    NOIP2010引水入城
    数差
    NOIP2016DAY2T1 组合数问题
    NOIP2016 D2T3 愤怒的小鸟
    NOIP双栈排序
    膜拜
    斐波那契数列
  • 原文地址:https://www.cnblogs.com/xiaowie/p/9391428.html
Copyright © 2011-2022 走看看