C#之委托学习三

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateDemo1
{
    class Program
    {
        static void One()
        {
            Console.WriteLine("one");
            throw new Exception("error in one");
        }
        static void Two()
        {
            Console.WriteLine("Two");
        }

        static void Main(string[] args)
        {
            /*  这也是多播委托 */
            Action action = One;
            action += Two;
            //按照调用顺序返回此多路广播委托的调用列表。
            Delegate[] delegates = action.GetInvocationList();
            foreach (Action ac in delegates)
            {
                try
                {
                    ac();
                }
                catch (Exception)//这里抛出异常  但还会迭代下一个方法
                {
                    Console.WriteLine("Exception caught");
                }
            }

            /*多播委托 因为第一个方法抛出了一 个异常 ,所以委托的迭代会停止 ,不再调用 Twoo方法
            没有指定当调用方法的顺序时 ,结果会有所不同*/
            try
            {
                action();
            }
            catch (Exception)//这里抛出异常 由于是顺序执行的  不会在迭代下一个方法
            {
                Console.WriteLine("Exception caught");
            }

            Console.ReadKey();
        }
    }
}

发布了70 篇原创文章 · 获赞 68 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/Rose_Girls/article/details/51332362