C#多播委托详解

包含多个方法的委托成为多播委托,调用多播委托,可以按照顺序连续调用多个方法,因此,委托的签名就必须返回void;
否则,就只能得到委托调用的最好一个方法的结果

1、多播委托可以用运算符"+"和"+="给委托添加方法调用,同样也可以用运算符"-"和"-="给委托删除方法调用

   void Hello(string s)
    {
        System.Console.WriteLine("  Hello, {0}!", s);
    }

    static void Goodbye(string s)
    {
        System.Console.WriteLine("  Goodbye, {0}!", s);
        throw new Exception("error");
    }

    Action<string> ac=Hello;
    ac+=Goodbye;

2、多播委托包含一个逐个调用委托集合,如果通过委托嗲用的其中一个方法抛出一个异常,整个迭代就会停止;、
为了避免这个问题,应该自己迭代方法列表。Delegate类定义GetInvocationList()方法,他返回一个Delegate
对象数组

  void Hello()
    {
        
    }

    static void Goodbye()
    {
        
    }

    Action ac=Hello;
    ac+=Goodbye;
    Delegate[] delegates=ac.GetInvocationList();
    foreach(Action action in delegates)
    {
     try
     {
      action();
      }catch(Exception)
     {
    }
    }

 

posted on 2017-12-20 15:42  weicanpeng  阅读(2278)  评论(0编辑  收藏  举报

导航