C# 委托/Func() 中 GetInvocationList() 方法的使用 | 接收委托多个返回值

在日常使用委托时,有以下常用方法

方法名称说明
 Clone  创建委托的浅表副本。
 GetInvocationList  按照调用顺序返回此多路广播委托的调用列表。
 GetMethodImpl  返回由当前的 MulticastDelegate 表示的静态方法。
 GetObjectData  用序列化该实例所需的所有数据填充 SerializationInfo 对象。
 MemberwiseClone  创建当前 Object 的浅表副本。
 RemoveImpl  调用列表中移除与指定委托相等的元素

GetInvocationList() 的用途

当委托有多个返回值时

当你编写一个 delegate委托 或 Func<>泛型委托 ,并为实例绑定多个方法时,每个方法都有一个返回值。可能会遇到这种情况:

  class Program
    {
        public static string a(string str)
        {
            Console.WriteLine("方法a");
            return str+"方法a";
        }
        public static string b(string str)
        {
            Console.WriteLine("方法b");
            return str + "方法b";
        }
        public static string c(string str)
        {
            Console.WriteLine("方法c");
            return str + "方法c";
        }
        static void Main(string[] args)
        {
            Func<string, string> func=a;
            func += b;
            func += c;
            Console.WriteLine(func("测试"));
            Console.ReadKey();
        }

    }

 调用委托后,只能获取到最后一个调用方法的返回值。


 

使用 GetInvocationList() 

GetInvocationList() 能够返回 这个委托的方法链表。

通过使用循环,把每个方法顺序调用一次,每次循环中都会产生当前调用方法的返回值。

    class Program
    {
        public static string a(string str)
        {
            Console.WriteLine("方法a");
            return str+"方法a";
        }
        public static string b(string str)
        {
            Console.WriteLine("方法b");
            return str + "方法b";
        }
        public static string c(string str)
        {
            Console.WriteLine("方法c");
            return str + "方法c";
        }
        static void Main(string[] args)
        {
            Func<string, string> func=a;
            func += b;
            func += c;
            var funclist = func.GetInvocationList();
            foreach (Func<string, string> f in funclist)
            {
                Console.WriteLine(f("测试"));
            }
            Console.ReadKey();
        }

  

 

相当于把委托里顺序调用的方法分离成一个列表,通过循环调用,循环获取。

转载于:https://www.cnblogs.com/whuanle/p/10035549.html

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值