[翻譯]在C#中使用Delegates

來源:互聯網
上載者:User

介紹
c#中的委託像c/c++中的函數指標.一個多重委託可以訂閱多個方法.一個委託可以在用來調用函數,具體調用哪個函數在啟動並執行時候被確定.

什麼是委託?為什麼需要他們?

委託是c#中型別安全的,可以訂閱一個或多個具有相同簽名方法的 函數指標.委託在c#中是參考型別.委託的必須和所指向的方法具有相同的簽名.

C#在System名字空間有個Delegate類,他提供了對委託的支援.委託有兩種類型:單一委託和多重委託
單一委託只能訂閱一個方法,而多重委託可以訂閱多個具有相同簽名的方法.

一個委託的簽名種類有以下幾方面組成
1.委託的名字
2.委託接受的參數
3.委託的傳回型別

如果沒有修飾符,委託不是public就是internal.下面是一個聲明委託的例子

聲明一個委託

public delegate void TestDelegate(string message);

 

在上面的例子中,委託的傳回型別是void,他接收一個string類型的參數.你可以用他訂閱和調用一個和他具有相同簽名的方法.一個委託必須在使用前進行執行個體化.

下面的語句就是執行個體化一個委託.TestDelegate t = new TestDelegate(Display);

實現一個單一委託using System;
public delegate void TestDelegate(string message); //Declare the delegate
class Test
...{
  public static void Display(string message)
  ...{
    Console.WriteLine("The string entered is : " + message);
  }
  static void Main()
  ...{
    TestDelegate t = new TestDelegate(Display); //Instantiate the delegate
    Console.WriteLine("Please enter a string");
    string message = Console.ReadLine();
    t(message); //Invoke the delegate
    Console.ReadLine();
  }
}

實現一個多重委託using System;
public delegate void TestDelegate();
class Test
...{
  public static void Display1()
  ...{
    Console.WriteLine("This is the first method");
  }
  public static void Display2()
  ...{
    Console.WriteLine("This is the second method");
  }
  static void Main()
  ...{
    TestDelegate t1 = new TestDelegate(Display1);
    TestDelegate t2 = new TestDelegate(Display2);
    t1 = t1 + t2; // Make t1 a multi-cast delegate
    t1(); //Invoke delegate
    Console.ReadLine();
  }
}

Created by jecray

執行上面這段代碼,會有如下顯示:
This is the first method
This is the second method

委託也可以和事件一起使用,本文只是簡單的介紹了delegate.

原文:http://aspalliance.com/1228_Working_with_Delegates_in_C

聯繫我們

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