介紹
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