CLR環境中內建了幾個常用委託(轉)

來源:互聯網
上載者:User

標籤:

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環境中內建了幾個常用委託(轉)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.