在 2.0 之前的 C# 版本中,聲明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法。
要将代碼塊傳遞為委托參數,建立匿名方法則是唯一的方法。例如:

// Create a handler for a click event

button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };

或

// Create a delegate instance

delegate void Del(int x);


// Instantiate the delegate using an anonymous method
Del d = delegate(int k)
{ /**//*
*/ };

如果使用匿名方法,則不必建立單獨的方法,是以減少了執行個體化委托所需的編碼系統開銷。
例如,如果建立方法所需的系統開銷是不必要的,在委托的位置指定代碼塊就非常有用。啟動新線程即是一個很好的示例。無需為委托建立更多方法,線程類即可建立一個線程并且包含該線程執行的代碼。

void StartThread()
{
System.Threading.Thread t1 = new System.Threading.Thread
(delegate()
System.Console.Write("Hello, ");
System.Console.WriteLine("World!");
});
t1.Start();
}

備注
匿名方法的參數的範圍是 anonymous-method-block。
在目标在塊外部的匿名方法塊内使用跳轉語句(如 goto、break 或 continue)是錯誤的。在目标在塊内部的匿名方法塊外部使用跳轉語句(如 goto、break 或 continue)也是錯誤的。
如果局部變量和參數的範圍包含匿名方法聲明,則該局部變量和參數稱為該匿名方法的外部變量或捕獲變量。例如,下面代碼段中的 n 即是一個外部變量:

int n = 0;
Del d = delegate()
{ System.Console.WriteLine("Copy #:{0}", ++n); };

與局部變量不同,外部變量的生命周期一直持續到引用該匿名方法的委托符合垃圾回收的條件為止。對 n 的引用是在建立該委托時捕獲的。
匿名方法不能通路外部範圍的 ref 或 out 參數。
在 anonymous-method-block 中不能通路任何不安全代碼。
代碼執行個體:
下面的示例示範執行個體化委托的兩種方法:
使委托與匿名方法關聯。
使委托與命名方法 (DoWork) 關聯。

// Declare a delegate

delegate void Printer(string s);


class TestClass
static void Main()
// Instatiate the delegate type using an anonymous method:
Printer p = delegate(string j)
System.Console.WriteLine(j);
};
// Results from the anonymous delegate call:
p("The delegate using the anonymous method is called.");
// The delegate instantiation using a named method "DoWork":
p = new Printer(TestClass.DoWork);
// Results from the old style delegate call:
p("The delegate using the named method is called.");
}
// The method associated with the named delegate:
static void DoWork(string k)
System.Console.WriteLine(k);

輸出結果: