匿名委託進階

   上面文章介紹了委託、匿名的定義,下面的例子則是由繁入簡,廢話很少說,直接上代碼: class Program
    {
        private   delegate int sum(int x, int y);
        private delegate int MyMulticastDelegate(int x, int y);
        static void Main(string[] args)
        {
          
            Console.WriteLine("委託方式一加法:");
            sum addsum = new sum(add);
            int y = addsum(2, 3);
            Console.WriteLine("委託方式一加法:2+3" + y);

           
            
            Console.WriteLine("多波委託:有的時候,咱們想要調用一個委託,但同時能夠執行多個方法(自定義事件中最爲常見),好比,一個工做文檔生成以後,系統要將生成文檔日誌,並且還要被保存到數據庫中,對於以上二個操做,若是隻想調用一個委託,就能夠順序完成,那麼使用多播委託,就能夠實現。");
            MyMulticastDelegate sumdele = new MyMulticastDelegate(add);

            MyMulticastDelegate subdele = new MyMulticastDelegate(sub);

            MyMulticastDelegate multicastDelegate = sumdele+subdele;

            multicastDelegate(2,2);


            Console.WriteLine("委託中的匿名方法(未簡化):");
            sum Nofuntion = new sum(delegate( int x,int i) { return x * i; });
            int k = Nofuntion(2,3);
            Console.WriteLine(k);

            Console.WriteLine("委託中的匿名方法(簡化):");
            sum  _sum =(int x, int m)=>{ return x * m; };   
            int z = Nofuntion(2, 3);
            Console.WriteLine(z);

            Console.ReadKey();
        }
      
        private static int add(int x, int y)
        {
            Console.WriteLine(x+y);
            return x + y;
        }
        private static int sub(int x, int y)
        {
            Console.WriteLine(x - y);
            return x - y;
        }
        private static void mulitey(int x, int y)
        {
            Console.WriteLine(x * y);
        }
    }
相關文章
相關標籤/搜索