介绍
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();
}
}
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();
}
}
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();
}
}
执行上面这段代码,会有如下显示:
This is the first method
This is the second method
委托也可以和事件一起使用,本文只是简单的介绍了delegate.
原文:http://aspalliance.com/1228_Working_with_Delegates_in_C