C#委託類似C/C++中的函數指針功能(它是類型安全的)。它定義了方法型別,可以當作方法的引數來進行傳遞。這樣可以增加程式碼的擴充性(不需用沉長的if-else或switch來判斷該用哪種方法)。以下是範例


以上是求的長方型,圓形和直角三角形的三個方法

此方法求該圖形的面積

在Main中執行
試想如果想要求得更多圖形的面積(多角形,正方形等等),就要修改GetShapeArea的方法,這樣會增加程式碼維護的難度。我們改用委託看看

委託(delegation)可以把方法當成引數,這樣就不需要像之前GetShapeArea方法用switch來判斷該圖形應該用那種計算面積的方法。如此可精簡程式碼和增加擴充性。
多播委託
我們可以將多個方法賦予委託。我們需要用到+和+=。以下是例子

執行起來會

若不想要圓形面積,則可以


匿名方法
委託也可以用匿名方式(使用delegate關鍵字)來定義方法。以下是範例

執行結果如下:

委託其它類型(Action,Func,predicate)
Action代表無法回值的委託,也就是void。Action<int, char>代表有兩個參數分別為(int和cha4)。
Func代表有返回值的委託。Func<int,string>表傳入參數為int,而返回值為string。
predicate代表返回值為bool。Predicate<int>表示傳入參數為int而返回值為bool。