首页 > 其他 > 详细

多播委托-迭代

时间:2014-10-30 14:58:13      阅读:241      评论:0      收藏:0      [点我收藏+]

概述

  在讲解多播委托的迭代之前,先讲一下,在委托调用的一连贯方法中,若有其中一个方法带有异常的情况:

  1)实现方法的类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace DelegateWithIteration {
 7     class Show {
 8         public static void One() {
 9             Console.WriteLine("one");
10         }
11 
12         public static void Two() {
13             Console.WriteLine("two");
14             throw new ArgumentException("Show::Two");   //带有异常的方法.
15         }
16 
17         public static void Three() {
18             Console.WriteLine("three");
19         }
20     }
21 }

  2)调用方法的多播委托类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace DelegateWithIteration {
 7     class Program {
 8         static void Main(string[] args) {
 9             Action action = Show.One;
10             action += Show.Two;
11             action += Show.Three;
12             try {
13                 action();   //直接调用多播委托.
14             }
15             catch (System.Exception ex) {
16                 Console.WriteLine("exception caught:" + ex.Message);
17             }
18         }
19     }
20 }

  可以测试,如果Show类中的 Two方法没有异常,则输出为:

1 one
2 two
3 three

  然而,如果委托调用的其中一个方法抛出异常,整个迭代就会停止.如下:

one
two
exception caught:Show::Two

  在方法Two抛出异常后,迭代停止,方法Three不会得到执行.解决的问题是:应该自己迭代方法列表,并对每个委托实例都进行异常捕捉:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace DelegateWithIteration {
 7     class Program {
 8         static void Main(string[] args) {
 9             Action actions = Show.One;
10             actions += Show.Two;
11             actions += Show.Three;
12             foreach (Action action in actions.GetInvocationList()) {    //自己迭代方法列表.
13                 try {   //对每个委托实例进行异常捕捉.
14                     action();
15                 }
16                 catch (System.Exception ex) {
17                     Console.WriteLine("exception caught:" + ex.Message);
18                 }
19             }
20         }
21     }
22 }

输出结果为:

one
two
exception caught:Show::Two
three

 

多播委托-迭代

原文:http://www.cnblogs.com/listened/p/4062595.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!