.net delegate(委託類型)

來源:互聯網
上載者:User

本質上,委託是指向若干方法的型別安全的對象(類似c++函數指標)。一個委託維持有三項重要的資訊:1,它要調用的方法的地址 2,方法的參數(如果有的話)3,方法的傳回值(如果有的話)。和c++函數指標不同的是,.net 委託可以指向靜態方法和執行個體方法。

 

    首先來看看如何定義一個委託(使用關鍵字delegate)

  1. // 這個委託可以指向任何接收兩個int參數並返回int值的方法
  2. //二元操作
  3. public delegate int BinaryOp(int x, int y);

你在聲明這個BinaryOp委託的時候,編譯器會為你產生這樣的一個類:

  1. sealed class BinaryOp : System.MulticastDelegate
  2. {
  3. public BinaryOp(object target, uint functionAddress);
  4. public int Invoke(int x, int y);
  5. public IAsyncResult BeginInvoke(int x, int y,
  6. AsyncCallback cb, object state);
  7. public int EndInvoke(IAsyncResult result);
  8. }

其中,Invoke是核心方法,顧名思義,是用來調用委託中維持的每個方法。BeginInvoke() 和EndInvoke()用來非同步呼叫當前的方法。這個需要你有多線程編程的背景,超出了本文要描述的範圍。這裡你只要理解委託其實暗中實現了本來要用多線程才能實現的功能。

待續……

初次認識委託,可能會覺得有點困惑。現在來看看一個完整的例子:

  1. namespace SimpleDelegate
  2. {
  3. // 這個委託可以指向任何接收兩個int參數並返回int值的方法
  4. //二元操作
  5. public delegate int BinaryOp(int x, int y);
  6. // 該類包含BinaryOp要指向的方法
  7. //
  8. public class SimpleMath
  9. {
  10. public static int Add(int x, int y)
  11. { return x + y; }
  12. public static int Subtract(int x, int y)
  13. { return x - y; }
  14. }
  15. class Program
  16. {
  17. static void Main(string[] args)
  18. {
  19. Console.WriteLine("***** Simple Delegate Example *****\n");
  20. // 建立一個指向SimpleMath.Add()的BinaryOp對象
  21. // 
  22. BinaryOp b = new BinaryOp(SimpleMath.Add);
  23. // 調用Add()方法 ,間接 使用了delegate 對象.
  24. Console.WriteLine("10 + 10 is {0}", b(10, 10));
  25. Console.ReadLine();
  26. }
  27. }
  28. }

聯繫我們

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