委托
委托(Delegate) 是存有对某个方法的引用的一种引用类型变量
委托的声明
访问域修饰符 delegate 返回值 委托名称 (参数列表)
public delegate int TestDelegate (int nTest);
上面的委托可被用于引用任何一个带有一个单一的 int 参数的方法,并返回一个 int 类型变量。
委托的实例化
int Add (int nTest)
{
nTest += nTest;
return nTest;
}
int Add (int nTest)
{
nTest /= nTest;
return nTest;
}
TestDelegate test1 = new TestDelegate(Add);
TestDelegate test1 = new TestDelegate(Divide);
一旦声明了委托类型,委托对象必须使用 new 关键字来创建,参数为函数名
此时 test1(5); 与 Add(5); 效果相同
委托的多播
委托对象可使用 “+” 运算符进行合并。一个合并委托调用它所合并的两个委托。只有相同类型的委托可被合并。"-" 运算符可用于从合并的委托中移除组件委托。
使用委托的这个有用的特点,可以创建一个委托被调用时要调用的方法的调用列表。这被称为委托的 多播 也叫 组播。