c#系列之各種lambda表達式


lambda表達式說白了就是一個匿名函數。

使用場景,舉個例子吧,就像我自己寫Android程序時,如果要綁定點擊事件,經常要寫一大堆幾乎一樣的格式的代碼,而這些代碼基本上沒有復用,所以也沒辦法寫一個函數啊,類啊來講話過程。

而lambda就是一個折中的辦法,在你寫一個函數,且只用在一個地方的時候,你可以寫這樣一個函數來簡化。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    delegate void test();
    delegate void test2(int x);
    class Program
    {
        static void Main(string[] args)
        {
            test mytest = delegate() { Console.WriteLine("wwx use the first"); };
            mytest += ()=> {Console.WriteLine("wwx use the second");};
          
            test2 mytest2 = delegate(int x) { Console.WriteLine("wwx use the first use the {0}",x);};
            mytest2 += (x) => {Console.WriteLine("wwx use the second use the {0}",x);};
            mytest2 += x =>{Console.WriteLine("wwx use the third use the {0}",x);};
            mytest2 += x => Console.WriteLine("use the four use the {0}",x);

            mytest();
            mytest2(2);
        }
    }
}


 
        

有幾個特點,對於只有一個參數的話,甚至可以不寫括號而且如果不是out,ref這樣的參數,可以不加類型(多個變量),如果方法體只有一句話,那么可以不寫大括號。

mytest2 += (x,y) => {Console.WriteLine("wwx use the second use the {0}",x);};



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM