C# 2.0 引入了透過 delegate 關鍵字實現匿名函數的功能,大幅減少樣板代碼。以按鈕點擊事件為例,傳統寫法需要單獨定義處理方法:
button1.Click += new EventHandler(button1_Click);
...
void button1_Click(Object sender, EventArgs e) {
// Do something, the button was clicked...
}
使用匿名函數可簡化為:
button1.Click += delegate(Object sender, EventArgs e) {
// Do something, the button was clicked...
};
關於用法可參考 Jeffrey Richter 的《Working with Delegates Made Easier with C# 2.0》。簡單來說,編譯器會自動將匿名函數代碼移至一個自動命名的方法中,完成原本需手工編寫的工作。例如:
class AClass {
static void CallbackWithoutNewingADelegateObject() {
ThreadPool.QueueUserWorkItem(delegate(Object obj) { Console.WriteLine(obj); }, 5);
}
}
會被編譯器轉換為:
class AClass {
static void CallbackWithoutNewingADelegateObject() {
ThreadPool.QueueUserWorkItem(new WaitCallback(__AnonymousMethod$00000002), 5);
}
private static void __AnonymousMethod$00000002(Object obj) {
Console.WriteLine(obj);
}
}
此時生成的方法為 static,因為匿名函數未捕獲任何實例成員。這是最簡單的情況——無捕獲變量的匿名方法直接編譯為靜態方法,效能與手寫代碼無異。