委托:类似于C/C++中函数的指针 是存有对某个方法的引用的一种 引用类型变量 引用可在运行时被改变
委托特别用于实现事件回调方法 所有的委托都派生于System.Delegate类
声明委托 public delegate int Test(string s) 可被用于引用任何一个带有单一string参数的方法 并返回一个int型变量
一旦声明了委托类型 委托类型必须使用new关键字来创造 与一个特定的方法有关
实例化委托
Test t1 = new Test(s)
委托的多播 :委托对象可使用“+”运算符进行合并 想同类型的委托才可以合并
可使用“-”运算符从合并的委托中移除组件委托
class TestDelegate
{
static int count = 10;
public static int AddCount(int p)
{
count += p;
return count;
}
public static int MulCount(int q)
{
count *= q;
return count;
}
public static int getCount()
{
return count;
}
public static void Main(string[] args)
{
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddCount);
NumberChanger nc2 = new NumberChanger(MulCount);
nc = nc1;
nc += nc2;
nc(5);
Console.WriteLine("Value of Count: {0}", getCount());
}
}