一、定义
委托(delegate),即委托别人办事;相当于代理、中介;委托某个方法来实现具体的功能。
委托是一种引用类型,是方法的抽象,声明时与方法相似,但不能称之为方法。
它存储的是一系列具有相同参数和返回类型的方法地址。
调用委托时,委托包含的所有方法都将被执行。
委托在使用时遵循三步走的原则,即定义声明委托、实例化委托以及调用委托。
二、声明
委托声明决定了可由该委托引用的方法。
语法:
修饰符 delegate 返回值类型 委托名称(参数列表);
例:
public delegate int MyDelegate(string s);
三、实例化委托及使用
一旦声明了委托类型,委托对象必须使用 new 关键字来创建,且与一个特定的方法有关。
创建委托时,传递到new语句的参数就像方法调用一样书写,不带有参数。
实例:
using System;
namespace DelegateApp
{
delegate int CalculateApp(int a,int b);
class DelegateTest
{
public static int Add(int a,int b)
{
return a + b;
}
public static int Sub(int a,int b)
{
return a - b;
}
static void Main(string[] args)
{
CalculateApp cal1 = new CalculateApp(Add);
CalculateApp cal2 = new CalculateApp(Sub);
Console.WriteLine("Add value:" + cal1(10, 10));
Console.WriteLine("Sub value:" + cal2(10, 5));
Console.ReadKey();
}
}
}
执行结果:
Add value:20
Sub value:5
四、委托的组播(也称为多播,Multicasting of a Delegate)
委托对象可以使用 加减 运算符来进行合并或移除;只有相同类型的委托才能被合并。
当委托对象中有多个方法时, 会依次执行委托中的方法,并返回最后一个方法的结果。
using System;
namespace DelegateApp
{
delegate int CalculateApp(int value);
class DelegateTest
{
static int num = 10;
public static int Add(int b)
{
num += b;
return num;
}
public static int Sub(int b)
{
num -= b;
return num;
}
public static int GetNum()
{
return num;
}
static void Main(string[] args)
{
CalculateApp cal;
CalculateApp cal1 = new CalculateApp(Add);
CalculateApp cal2 = new CalculateApp(Sub);
cal = cal1;
cal += cal2;
Console.WriteLine("The value of Multicasting:" + GetNum());
Console.ReadKey();
}
}
}
执行结果:
The value of Multicasting:10
委托的基础介绍与使用就到这里啦。