C# 教程login
C# 教程
作者:php.cn  更新時間:2022-04-11 14:06:23

C# 委託(Delegate)



C# 中的委託(Delegate)類似於 C 或 C++ 中函數的指標。 委託(Delegate) 是存有對某個方法的引用的一種引用類型變數。引用可在運行時被改變。

委託(Delegate)特別用於實作事件和回呼方法。所有的委託(Delegate)都衍生自 System.Delegate 類別。

聲明委託(Delegate)

委託聲明決定了可由該委託引用的方法。委託可指向一個與其具有相同標籤的方法。

例如,假設有一個委託:

public delegate int MyDelegate (string s);

上面的委託可被用來引用任何一個帶有一個單一的string 參數的方法,並傳回一個int 類型變數。

聲明委託的語法如下:

delegate <return type> <delegate-name> <parameter list>

實例化委託(Delegate)

一旦宣告了委託類型,委託物件必須使用new 關鍵字來創建,且與一個特定的方法有關。當建立委託時,傳遞到 new 語句的參數就像方法呼叫一樣書寫,但不帶有參數。例如:

public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

下面的實例示範了委託的宣告、實例化和使用,該委託可用於引用具有一個整數參數的方法,並傳回一個整數值。

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 10;
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }

      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }

      static void Main(string[] args)
      {
         // 创建委托实例
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         // 使用委托对象调用方法
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

當上面的程式碼被編譯和執行時,它會產生下列結果:

Value of Num: 35
Value of Num: 175

委託的多播(Multicasting of a Delegate)

委託物件可使用"+" 運算子進行合併。一個合併委託呼叫它所合併的兩個委託。只有相同類型的委託可合併。 "-" 運算子可用於從合併的委託中移除組件委託。

使用委託的這個有用的特點,您可以建立一個委託被呼叫時要呼叫的方法的呼叫清單。這被稱為委託的 多播(multicasting),也叫組播。下面的程式示範了委託的多重播放:

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 10;
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }

      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }

      static void Main(string[] args)
      {
         // 创建委托实例
         NumberChanger nc;
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         nc = nc1;
         nc += nc2;
         // 调用多播
         nc(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

當上面的程式碼被編譯和執行時,它會產生下列結果:

Value of Num: 75

委託(Delegate)的用途

下面的實例示範了委託的用法。委託 printString 可用來引用帶有一個字串作為輸入的方法,並不會回傳任何東西。

我們使用這個委託來呼叫兩個方法,第一個把字串印到控制台,第二個把字串印到檔案:

using System;
using System.IO;

namespace DelegateAppl
{
   class PrintString
   {
      static FileStream fs;
      static StreamWriter sw;
      // 委托声明
      public delegate void printString(string s);

      // 该方法打印到控制台
      public static void WriteToScreen(string str)
      {
         Console.WriteLine("The String is: {0}", str);
      }
      // 该方法打印到文件
      public static void WriteToFile(string s)
      {
         fs = new FileStream("c:\message.txt",
         FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }
      // 该方法把委托作为参数,并使用它调用方法
      public static void sendString(printString ps)
      {
         ps("Hello World");
      }
      static void Main(string[] args)
      {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }
}

當上面的程式碼被編譯和執行時,它會產生下列結果:

The String is: Hello World

PHP中文網