C#委託


C# 委託類似於C語言C++中函式的指標。委託是一個參照型別變數,它儲存對方法的參照。 參照可以在執行時更改。

委託一般用於實現事件和回撥方法。所有委託都隱式地從System.Delegate類派生。

宣告委託

委託宣告確定委託可參照的方法。委託可以參照一個方法,它具有與委託相同的簽名。

例如,考慮下面一個委託:

public delegate int MyDelegate (string s);

上述委託可用於參照具有單個字串引數並返回int型別變數的任何方法。

委託宣告的語法是:

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

範例化委託

當宣告了一個委託型別後,必須要使用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)
      {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);

         //calling the methods using the delegate objects
         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

委託組播

代理物件可以使用「+」運算子來組合。一個委託呼叫它由兩個委託組成。只能組合相同型別的委託。「-」運算子可用於從組合委託中刪除元件委託。

使用委託的這個屬性,可以建立一個方法的呼叫列表,該方法將在呼叫委託時呼叫。這稱為委託組播。以下程式演示了一個委託組播:

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
    class TestDelegate
    {
        static int num = 100;
        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)
        {
            //create delegate instances
            NumberChanger nc;
            NumberChanger nc1 = new NumberChanger(AddNum);
            NumberChanger nc2 = new NumberChanger(MultNum);
            nc = nc1;
            nc += nc2;

            //calling multicast
            nc(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }
}

當上述程式碼被編譯並執行時,它產生以下結果:

Value of Num: 525

使用委託

以下範例演示了使用委託。委託printString可用於參照方法,該方法將字串作為輸入,並且不返回任何內容。

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

using System;
using System.IO;

namespace DelegateAppl
{
   class PrintString
   {
      static FileStream fs;
      static StreamWriter sw;

      // delegate declaration
      public delegate void printString(string s);

      // this method prints to the console
      public static void WriteToScreen(string str)
      {
         Console.WriteLine("The String is: {0}", str);
      }

      //this method prints to a file
      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();
      }

      // this method takes the delegate as parameter and uses it to
      // call the methods as required
      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