多播委托执行时遇到异常跳过异常继续执行的方法

static void Main(string[] args)
        {
            
            Action action = One;
            action += Two;

            Delegate[] delegates = action.GetInvocationList();
            foreach(Action item in delegates)
            {
                try
                {
                    item();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            
            Console.ReadKey();
        }
        static void One()
        {
            Console.WriteLine("One");
            throw new Exception("one Exception");
        }

        static void Two()
        {
            Console.WriteLine("Two");
        }

  主要是用了GetInvocationList这个方法,不仅可以绕过异常,还可以依次返回执行的结果,代码如下。

 

Func <string> action2 = T1;
            action2 += T2;

            Delegate[] delegates = action2.GetInvocationList();
            foreach(Func<string> item in delegates)
            {
                try
                {
                   Console.WriteLine(item());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            
            Console.ReadKey();
        }

        static string T1()
        {
            return "T1";
        }

        static string T2()
        {
            return "T2";
        }

  

posted @ 2017-12-07 16:58  刚出炉的程序猿  阅读(341)  评论(0)    收藏  举报