1. 程式人生 > >C#之Lambda表達式

C#之Lambda表達式

-a spa con close 運行 threading ret cnblogs .cn

Lambda表達式是為了更好的使用匿名函數,這裏介紹一下lambda表達式的語法。

=> 是Lambda表達式必須的符號。=>左邊代表函數的參數,右邊為函數體。

Lambda表達式的使用可以參考下面的情況。

技術分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace MyPrograms
 8 {
 9     class Program
10     {
11 static void Main(string[] args) 12 { 13 //如果lambda沒有參數並且只有一句話的時候 14 Action a = () => Console.WriteLine("沒有參數並且只有一句話的時候"); 15 a(); 16 //只有一個參數沒有返回值 17 Action<int> b = num1 => Console.WriteLine(num1); 18 b(100
); 19 //有多個參數,一個返回值 20 //Func尖括號裏代表最後一個是返回值類型,其余為參數 21 Func<int, int, int> c = (num1, num2) => { 22 Console.Write(num1); 23 Console.Write(" "); 24 Console.WriteLine(num2); 25 return num1 + num2;
26 }; 27 Console.WriteLine(c(5, 6)); 28 Console.ReadKey(); 29 } 30 } 31 }
View Code

運行結果如圖:

技術分享

C#之Lambda表達式