關於委託(2)

來源:互聯網
上載者:User

      前面使用的委託只包含一個方法調用。調用委託的次數與調用方法的次數相同。如果要調用多個方法,就需要多次顯示調用這個委託。其實委託也可以包含多個方法,這種委託就是多播委託。如果調用多路委託,就可以按順序連續調用多個方法。

      多播委託派生於System.MulticastDelegate,它的Combine方法允許把多個方法調用連結在一起,我們可以通過+和+=來向委託添加調用方法,也可以用-和-=刪除其中的調用方法。如:

    class Program
    {
        private delegate void DoubleOP(double x);
        static void Main(string[] args)
        {       
            DoubleOP operations = MathsOpration.MutiplybyTwo;
            operations += MathsOpration.Square;
            ProcessAndDisplay(operations, 2.0);
            ProcessAndDisplay(operations, 7.9);
            ProcessAndDisplay(operations, 1.414);

            Console.ReadKey();
        }
        static void ProcessAndDisplay(DoubleOP action, double value)
        {
            Console.WriteLine();
            Console.WriteLine("ProcessAndDisplayNumber called with value={0}", value);
            action(value );
          
        }

    }
    class MathsOpration
    {
        public static void  MutiplybyTwo(double value)
        {
            double result = value * 2;
            Console.WriteLine ("Mutiplying by 2:{0} gives {1}",value ,result  );
        }
        public static void  Square(double value)
        {
            double result = value * value;
            Console.WriteLine("Squaring :{0} gives {1}",value,result );
        }
    }

 

結果:

 

注意:

      1、多播委託中委託的簽名必須返回void;否則,就只能得到委託調用的最後一個方法的結果。

      2、如果使用多播委託,就應該注意同一個委託調用鏈的順序並未正式定義,因此避免編寫依賴於以特定順序調用方法的代碼;

      3、多播委託包含一個逐個調用的委託集合。如果通過委託調用的一個方法拋出了異常,整個迭代就會停止。

        解決方案:手動迭代方法列表

        原始碼如下,大家有空可以去嘗試下:

     

    //彈出異常,終止迭代的代碼

    public delegate void DemoTrying();
    class Program
    {
        static void Main()
        {
            DemoTrying d = One;
            d += Two;
            try
            {
                d();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message );
            }
            Console.ReadKey();

        }
        static void One()
        {
            Console.WriteLine("one");
            throw new Exception("Error in one");
        }
        static void Two()
        {
            Console.WriteLine("two");
        }
    }  

 

 

    //更改之後的代碼

    public delegate void DemoTrying();
    class Program
    {
        static void Main()
        {
            DemoTrying d = One;
            d += Two;
            Delegate [] delegates=d.GetInvocationList ();
            foreach (DemoTrying d1 in delegates)
            {
                try
                {
                    d1();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            Console.ReadKey();

        }
        static void One()
        {
            Console.WriteLine("one");
            throw new Exception("Error in one");
        }
        static void Two()
        {
            Console.WriteLine("two");
        }
    }  

 

 

委託的知識是十分重要的,也是十分廣泛的。在此提下委託涉及的其他知識,有意向的同學可以去看下:匿名方法,Lambda運算式,傳回型別協變和參數類型抗變等等。其中匿名方法,Lambda運算式有助於簡化委託的代碼量(以人為本哦)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.