按鈕點擊事件綁定演進:
// C# 1.x:顯式方法
addButton.Click += new EventHandler(AddClick);
void AddClick(object s, EventArgs e) { listBox.Items.Add(textBox.Text); }
// C# 2.0:匿名方法
addButton.Click += delegate { listBox.Items.Add(textBox.Text); };
// C# 3.0:Lambda
addButton.Click += (s, e) => listBox.Items.Add(textBox.Text);
// => 讀作 "goes to",左參數右表達式/語句塊
// 顯式類型
(int x) => x + 1
// 隱式類型(推薦,編譯器推斷)
(x, y) => x * y
// 單參數可省略括號
x => x * 2
static void AnonMethod(List list)
{
var even = list.FindAll(delegate(string s) { return s.Length % 2 == 0; });
foreach (var s in even) Console.WriteLine(s);
}
static void LambdaExample(List list)
{
var even = list.FindAll(s => s.Length % 2 == 0);
foreach (var s in even) Console.WriteLine(s);
}
namespace LambdaExample
{
public delegate bool KeyValueFilter(K key, V value);
static class Program
{
static void Main()
{
var list = new List { "AA", "ABC", "DEFG", "XYZ" };
AnonMethod(list);
LambdaExample(list);
// 多參數 Lambda 實戰
var clothes = new Dictionary
{ {"Jeans",20}, {"Shirts",15}, {"Pajamas",9}, {"Shoes",9} };
var shortage = clothes.FilterBy((name, count) => name == "Shoes" && count < 10);
}
static void AnonMethod(List list) { ... }
static void LambdaExample(List list) { ... }
}
public static class Extensions
{
public static Dictionary FilterBy(
this Dictionary items, KeyValueFilter filter) { ... }
}
}
delegate、return、大括號、類型聲明Expression<TDelegate> 時生成表達式樹,支撐 LINQ to SQL/EFLambda 表達式是 C# 邁向函數式編程的關鍵語法糖:以極簡語法表達行為,編譯器負責生成委托/表達式樹。從匿名方法到 Lambda,不僅是語法簡化,更是將「代碼作為數據」的理念推向主流,直接支撐了 LINQ 的誕生。