在C#编程中,委托是一种引用类型,它可以封装一个或多个方法,当委托被调用时,所有封装的方法会按顺序执行,这种多个方法组合形成的委托就是委托链。通过+=和-=操作符,我们可以方便地管理委托链中的方法。

委托的基础定义
要使用委托链,首先需要定义委托类型,委托的定义需要和方法签名匹配,包括返回值类型和参数列表。下面是一个简单的委托定义示例:
// 定义一个无参数无返回值的委托类型 public delegate void MyDelegate();
使用+=构建委托链
当我们声明一个委托变量后,可以直接将方法赋值给委托,之后使用+=操作符就可以把更多的方法添加到委托链中。示例如下:
class Program
{
// 定义和委托签名匹配的方法
static void Method1()
{
Console.WriteLine("执行方法1");
}
static void Method2()
{
Console.WriteLine("执行方法2");
}
static void Method3()
{
Console.WriteLine("执行方法3");
}
static void Main(string[] args)
{
// 初始化委托,赋值第一个方法
MyDelegate myDelegate = Method1;
// 使用+=添加第二个方法到委托链
myDelegate += Method2;
// 使用+=添加第三个方法到委托链
myDelegate += Method3;
// 调用委托,所有链中的方法会按顺序执行
myDelegate();
}
}
上述代码执行后,控制台会依次输出执行方法1、执行方法2、执行方法3,说明三个方法都已经被加入到委托链中,调用委托时按顺序执行。
使用-=移除委托链中的方法
如果我们需要从委托链中移除某个方法,可以使用-=操作符。需要注意的是,只有之前通过+=添加到委托链的方法才能被移除,而且如果委托链中有多个相同的方法,-=只会移除最后一个匹配的方法。示例如下:
static void Main(string[] args)
{
MyDelegate myDelegate = Method1;
myDelegate += Method2;
myDelegate += Method3;
myDelegate += Method2; // 再次添加Method2到委托链
Console.WriteLine("移除前调用委托:");
myDelegate();
// 使用-=移除Method2,只会移除最后添加的那个Method2
myDelegate -= Method2;
Console.WriteLine("移除后调用委托:");
myDelegate();
}
执行上述代码,第一次调用委托会输出方法1、方法2、方法3、方法2,第二次调用委托会输出方法1、方法2、方法3,说明最后一个添加的Method2被成功移除了。
委托链的常见注意事项
空委托的处理
如果委托变量没有被赋值,或者委托链中的所有方法都被移除,此时委托的值为null,直接调用会抛出空引用异常。因此调用委托前需要判断是否为空:
static void Main(string[] args)
{
MyDelegate myDelegate = Method1;
myDelegate += Method2;
// 移除所有方法
myDelegate -= Method1;
myDelegate -= Method2;
// 调用前判断委托是否为空
if (myDelegate != null)
{
myDelegate();
}
else
{
Console.WriteLine("委托链为空,无法调用");
}
}
有返回值的委托链
如果委托有返回值,调用委托链时,只有最后一个方法的返回值会被返回,前面的方法的返回值会被忽略。示例如下:
// 定义有返回值的委托
public delegate int CalculateDelegate(int a, int b);
class Program
{
static int Add(int a, int b)
{
Console.WriteLine("执行加法");
return a + b;
}
static int Multiply(int a, int b)
{
Console.WriteLine("执行乘法");
return a * b;
}
static void Main(string[] args)
{
CalculateDelegate calc = Add;
calc += Multiply;
int result = calc(2, 3);
Console.WriteLine($"委托链返回结果:{result}");
}
}
上述代码执行后,会先输出执行加法、执行乘法,最后返回的结果是6,也就是Multiply方法的返回值,Add方法的返回值5被忽略了。
委托链的实际应用场景
委托链最常见的应用场景是事件机制,C#中的事件本质就是委托链的封装,通过+=订阅事件,-=取消订阅事件,当事件触发时,所有订阅的方法都会被执行。另外在回调函数的实现中,委托链也可以让多个回调方法同时响应同一个操作,提升代码的扩展性。