C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。在C#中方法不能作为参数直接传递,必须使用委托(用来委托方法)。delegate(委托)是一种特殊的引用类型,它将方法也作为特殊的对象封装起来,从而将方法作为变量、参数或者返回值传递。委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。使用一个委托有三个步骤:
- 定义委托
- 实例化委托
- 将指定的方法添加到委托对象中
例子:
delegate int plus(int x, int y); // 1. 定义委托
static void Main(string[] args)
{
plus del_p; // 2. 实例化委托
del_p = new plus(addition); // 3. 将方法添加到实例化委托对象中
int n = del_p(1, 2);
Console.Write(n);
}
static int addition(int x, int y)
{
return x + y;
}
C#允许直接把方法名赋给委托,所以下面的三种写法也正确:
plus del_p = new plus(addition);
plus del_p2 = addition;
del_p = addition;
委托完全可以被当做普通类型对待,比如可以加减、赋值、构建数组。
委托数组
委托可以构建数组,意味着一组同样返回类型和参数类型的方法。
delegate int MathFunc(int x, int y);
static void Main(string[] args)
{
MathFunc[] fs = new MathFunc[]
{
substract,
addition,
product,
division
};
int n = fs[0](1, 2); // -1
}
static int division( int x, int y)
{
return x / y;
}
static int substract(int x, int y)
{