標籤:
CLR環境中給我們內建了幾個常用委託Action、 Action<T>、Func<T>、Predicate<T>,一般我們要用到委託的時候,盡量不要自己再定義一 個委託了,就用系統內建的這幾個已經能夠滿足大部分的需求,且讓代碼符合規範。
一、Action
Action封裝的方法沒有參數也沒有傳回值,聲明原型為:
1 public delegate void Action();
用法如下:
public void Alert() { Console.WriteLine("這是一個警告"); } Action t = new Action(Alert); // 執行個體化一個Action委託 t();
如果委託的方法裡的語句比較簡短,也可以用Lambd運算式直接把方法定義在委託中,如下:
Action t = () => { Console.WriteLine("這是一個警告"); };
t();
二、Action<T>
Action<T>是Action的泛型實現,也是沒有傳回值,但可以傳入最多16個參數,兩個參數的聲明原型為:
1 public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
用法如下:
private void ShowResult(int a, int b){ Console.WriteLine(a + b);} Action<int, int> t = new Action<int, int>(ShowResult);//兩個參數但沒傳回值的委託t(2, 3);
同樣也可以直接用Lambd運算式直接把方法定義在委託中,代碼如下:
Action<int, int> t = (a,b) => { Console.WriteLine(a + b); };
t(2, 3);
三、Func<T>
Func<T>委託始終都會有傳回值,傳回值的類型是參數中最後一個,可以傳入一個參數,也可以最多傳入16個參數,但可以傳入最多16個參數,兩個參數一個傳回值的聲明原型為:
1 public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
用法如下:
public bool Compare(int a, int b){ return a > b;} Func<int, int, bool> t = new Func<int, int, bool>(Compare);//傳入兩個int參數,返回bool值bool result = t(2, 3);
同樣也可以直接用Lambd運算式直接把方法定義在委託中,代碼如下:
Func<int, int, bool> t = (a, b) => { return a > b; };
bool result = t(2, 3);
四 、Predicate<T>
Predicate<T>委託表示定義一組條件並確定指定對象是否符合這些條件的方法,傳回值始終為bool類型,聲明原型為:
1 public delegate bool Predicate<in T>(T obj);
用法如下:
public bool Match(int val){ return val > 60;} Predicate<int> t = new Predicate<int>(Match); //定義一個比較委託int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 }; int first = Array.Find(arr, t); //找到數組中大於60的第一個元素
同樣也可以直接用Lambd運算式直接把方法定義在委託中,代碼如下:
Predicate<int> t = val => { return val > 60;}; //定義一個比較委託
int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 };
int first = Array.Find(arr, t); //找到數組中大於60的第一個元素
總結:
如果要委託的方法沒有參數也沒有傳回值就想到Action
有參數但沒有傳回值就想到Action<T>
無參數有傳回值、有參數且有傳回值就想到Func<T>
有bool類型的傳回值,多用在比較子的方法,要委託這個方法就想到用Predicate<T>
CLR環境中內建了幾個常用委託(轉)