講解C#委託(DELEGATE)

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

This image has an empty alt attribute; its file name is delegateP1.png
This image has an empty alt attribute; its file name is delegateP2.png

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

This image has an empty alt attribute; its file name is delegateP3.png

此方法求該圖形的面積

This image has an empty alt attribute; its file name is delegateP4.png

在Main中執行

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

This image has an empty alt attribute; its file name is delegateP5.png

委託(delegation)可以把方法當成引數,這樣就不需要像之前GetShapeArea方法用switch來判斷該圖形應該用那種計算面積的方法。如此可精簡程式碼和增加擴充性。

多播委託

我們可以將多個方法賦予委託。我們需要用到+和+=。以下是例子

This image has an empty alt attribute; its file name is delegateP6.png

執行起來會

This image has an empty alt attribute; its file name is delegateP7.png

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

This image has an empty alt attribute; its file name is delegateP8.png
This image has an empty alt attribute; its file name is delegateP9.png

匿名方法

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

This image has an empty alt attribute; its file name is delegateP10.png

執行結果如下:

This image has an empty alt attribute; its file name is delegateP11.png

委託其它類型(Action,Func,predicate)

Action代表無法回值的委託,也就是void。Action<int, char>代表有兩個參數分別為(int和cha4)。

Func代表有返回值的委託。Func<int,string>表傳入參數為int,而返回值為string。

predicate代表返回值為bool。Predicate<int>表示傳入參數為int而返回值為bool。