C#4.0新特性學習(三)—泛型委派

來源:互聯網
上載者:User

為了方便開發,.Net類庫預定好了幾個泛型委派。

1 Func系列委託    

Func系列委託的定義:
public delegate TResult Func<TResult>();       
public delegate TResult Func<T,TResult>(T arg);       
public delegate TResult Func<T1,T2,TResult>(T1 arg1,T2 arg2);       
public delegate TResult Func<T1,T2,T3,TResult>(T1 arg1,T2 arg2,T3 arg3);       
public delegate TResult Func<T1,T2,T3,T4,TResult>(T1 arg1,T2 arg2,T3 arg3,T4 arg4);
Func委託聲明的最後一個泛型型別參數是委託所接收方法的傳回值類型,前面的泛型參數就是委託所接收方法的形參類型。

 例子: 

 static int Add(int x, int y)
 {
     return x + y;
 }

 Func<int, int, int> func = Add;
 int sum = func(5, 6);
 Console.WriteLine(sum);

2 Action系列委託與MethodInvoker
Func泛型委派所能接收的方法都有傳回值,Action系列委託是接收返回void的系統預定義委託
public delegate void Action();
public delegate void Action<T>(T obj);
public delegate void Action<T1,T2>(T1 arg1,T2 arg2);
public delegate void Action<T1,T2,T3>(T1 arg1,T2 arg2,T3 arg3);

例子:

 static void Show(string str)
 {
     Console.WriteLine(str);
 }

 Action<string> action = Show;
 action("Hello world!");
 Console.ReadKey();

MethodInvoker委託位於System.Windows.Forms中,聲明如下:
public delegate void MethodInvoker();和無型別參數的Action委託等價,用法也一樣。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.