调用多播委托时的异常处理---5

34 阅读1分钟

多播委托

  1. 持有多个方法引用的委托,称为多播委托(多路广播委托);
  2. 在调用多播委托时,如果调用列表中的某一个方法抛出异常,整个迭代就会停止,该方法之后的所有方法将不会被调用。
  3. Delegate类的GetInvocationList()方法,返回一个Delegate对象数组,该数组种的每个元素都是一个委托对象,该对象持有原多播委托调用列表中一个方法。(解决方法异常终止程序执行的方式。)
 internal class ExceptionTest
    {
        //方法1
        public static void MethodOne()
        {
            Console.WriteLine("MethodOne");
            //抛出异常
            throw new Exception("Error in MethodOne");
        }

        //方法2
        public static void MethodTwo()
        {
            Console.WriteLine("MethodOne");
        }
    }
 //异常委托
    public delegate void ExceptionDelegate();
    
      //异常委托测试
        static void ExceptionDelegateTest()
        {
            ExceptionDelegate exceptionDelegate = ExceptionTest.MethodOne;
            exceptionDelegate += ExceptionTest.MethodTwo;
            exceptionDelegate += ExceptionTest.MethodOne;
            exceptionDelegate += ExceptionTest.MethodTwo;

            //为了避免一个委托方法带来的异常导致程序不能正常运行,使用该方法,可以分发方法
            //到不同的委托变量
            Delegate[] delegates=exceptionDelegate.GetInvocationList();
            //遍历数组的第一种方式
            for (int i = 0; i < delegates.Length; i++)
            {
                try
                {
                    //调用委托,需要进行强制类型转换,将Delegate转为ExceptionDelegate
                    (delegates[i] as ExceptionDelegate)();
                }
                //捕获异常
                catch
                {
                    Console.WriteLine("Exception Caught!!!");
                }
            }
            
            //遍历数组的第二种方式,foreach
            //foreach(ExceptionDeleagate ex in delegates)
            // try
            //    {
                    //调用委托,需要进行强制类型转换,将Delegate转为ExceptionDelegate
             //       ex();
             //   }
                //捕获异常
             //   catch
             //   {
             //       Console.WriteLine("Exception Caught!!!");
              //  }
            }
            Console.Read ();
        }