多播委托

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

 

无返回值的多播委托

   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";
        }

 

转载于:https://www.cnblogs.com/xiaowie/p/9391428.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值