今天學習一下c#中的泛型委托。
1.一般的委托,delegate,可以又傳入參數(<=32),聲明的方法為 public delegate void SomethingDelegate(int a);
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace delegateSummary {
8 public delegate void GetIntDelegate(int a); //聲明一個委托
9 public class getIntClass {
10 public static void SetDelegateString(int a,GetIntDelegate getIntDelegate) {//使用委托
11 getIntDelegate(a);
12 }
13 public void getInt1(int a) { //方法1
14 Console.WriteLine("getInt1方法調用,參數為:" + a);
15 }
16 public void getInt2(int a) { //方法2
17 Console.WriteLine("getInt2方法調用,參數為:" + a);
18 }
19 }
20 class Program {
21 static void Main(string[] args) {
22 getIntClass gc=new getIntClass();
23 getIntClass.SetDelegateString(5, gc.getInt1); //方法1,2作為委托的參數
24 getIntClass.SetDelegateString(10, gc.getInt2);
25 Console.WriteLine("=====================");
26 GetIntDelegate getIntDelegate;
27 getIntDelegate = gc.getInt1; //將方法1,2綁定到委托
28 getIntDelegate += gc.getInt2;
29 getIntClass.SetDelegateString(100, getIntDelegate);
30 Console.Read();
31 }
32 }
33 }
輸出結果,注意兩種方式的不同,第一種將方法作為委托的參數,第二種是將方法綁定到委托。

2.泛型委托之Action,最多傳入16個參數,無返回值。
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace delegateSummary {
8 class Program {
9 static void Main(string[] args) {
10 TestAction<string>(getString, "WhiteTaken"); //傳入方法
11 TestAction<int>(getInt, 666);
12 TestAction<int, string>(getStringAndInt, 666, "WhiteTaken");
13 Console.Read();
14 }
15 public static void TestAction<T>(Action<T> action,T p1) { //Action傳入一個參數測試
16 action(p1);
17 }
18 public static void TestAction<T, P>(Action<T, P> action, T p1, P p2) { //Action傳入兩個參數測試
19 action(p1,p2);
20 }
21 public static void getString(string a) { //實現int類型打印
22 Console.WriteLine("測試Action,傳入string,並且傳入的參數為:" +a);
23 }
24
25 public static void getInt(int a) { //實現String類型打印
26 Console.WriteLine("測試Action,傳入int,並且傳入的參數為:" + a);
27 }
28
29 public static void getStringAndInt(int a, string name) { //實現int+string類型打印
30 Console.WriteLine("測試Action,傳入兩參數,並且傳入的參數為:" + a+":"+name);
31 }
32 }
33 }
測試結果:

3.泛型委托之Func,最多傳入16個參數,有返回值。(寫法與Action類似,只是多了返回值)
4.泛型委托之predicate(不是很常用),返回值為bool,用在Array和list中搜索元素。(沒有用到過,等用到了再更新)