zoukankan      html  css  js  c++  java
  • 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)
         {
        }
        }
  • 相关阅读:
    Dictionary集合 字典
    装箱和拆箱
    List< >泛型集合
    Hashtable 键值对集合
    File 类 的基本操作
    简体转换繁体
    ArrayList集合长度的问题
    ArrayList  集合
    里式转换
    字符串中常用的方法
  • 原文地址:https://www.cnblogs.com/weicanpeng/p/8074093.html
Copyright © 2011-2022 走看看