面向云技术架构 - 痴者工良

  • 首页
  • 工良写的电子书
    • kubernetes 教程
    • 从 C# 入门 Kafka
    • 多线程和异步
    • 动态编程-反射、特性、AOP
    • 表达式树
  • 本站文章导航
  • 隐私政策
愿有人陪你颠沛流离
遇到能让你付出的事物或者人,都是一种运气。
能遇到,就该珍惜。或许你们最终没能在一起,但你会切实地感受到力量。
正因为这样,那段相遇才变得有价值,才没有辜负这世间的每一段相遇。
  1. 首页
  2. .NET
  3. 正文

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

2019年12月15日 1756点热度 0人点赞 1条评论
内容纲要

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

方法名称 说明
 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();
        }

  

 

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

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: c func getinvocationlist 委托 返回值
最后更新:2019年12月15日

痴者工良

高级程序员劝退师

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

文章目录
  • GetInvocationList() 的用途
    • 当委托有多个返回值时
    • 使用 GetInvocationList() 

COPYRIGHT © 2022 whuanle.cn. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

粤ICP备18051778号

粤公网安备 44030902003257号