C# 委托類似于C語(yǔ)言或C++中函數(shù)的指針。委托是一個(gè)引用類型變量,它保存對(duì)方法的引用。 引用可以在運(yùn)行時(shí)更改。
委托一般用于實(shí)現(xiàn)事件和回調(diào)方法。所有委托都隱式地從System.Delegate類派生。
委托聲明確定委托可引用的方法。委托可以引用一個(gè)方法,它具有與委托相同的簽名。
例如,考慮下面一個(gè)委托:
public delegate int MyDelegate (string s);
上述委托可用于引用具有單個(gè)字符串參數(shù)并返回int類型變量的任何方法。
委托聲明的語(yǔ)法是:
delegate <return type> <delegate-name> <parameter list>
當(dāng)聲明了一個(gè)委托類型后,必須要使用new關(guān)鍵字創(chuàng)建一個(gè)委托對(duì)象,并將其與特定的方法相關(guān)聯(lián)。創(chuàng)建代理時(shí),傳遞給新表達(dá)式的參數(shù)類似于方法調(diào)用,但不包含方法的參數(shù)。 例如:
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
以下示例演示了可以用于引用取整數(shù)參數(shù)并返回整數(shù)值的方法委托的聲明,實(shí)例化和使用。
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();
}
}
}
當(dāng)上述代碼被編譯并執(zhí)行時(shí),它產(chǎn)生以下結(jié)果:
Value of Num: 35
Value of Num: 175
代理對(duì)象可以使用“+”運(yùn)算符來(lái)組合。一個(gè)委托調(diào)用它由兩個(gè)委托組成。只能組合相同類型的委托。“-”運(yùn)算符可用于從組合委托中刪除組件委托。
使用委托的這個(gè)屬性,可以創(chuàng)建一個(gè)方法的調(diào)用列表,該方法將在調(diào)用委托時(shí)調(diào)用。這稱為委托組播。以下程序演示了一個(gè)委托組播:
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();
}
}
}
當(dāng)上述代碼被編譯并執(zhí)行時(shí),它產(chǎn)生以下結(jié)果:
Value of Num: 525
以下示例演示了使用委托。委托printString可用于引用方法,該方法將字符串作為輸入,并且不返回任何內(nèi)容。
使用這個(gè)委托來(lái)調(diào)用兩個(gè)方法,第一個(gè)將字符串打印到控制臺(tái),第二個(gè)打印到一個(gè)文件中:
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();
}
}
}
當(dāng)上述代碼被編譯并執(zhí)行時(shí),它產(chǎn)生以下結(jié)果:
The String is: Hello World