在c#中,可以使用`delegate.combine()`静态方法或`+`运算符将多个委托实例合并为一个多播委托(multicast delegate)。调用该多播委托时,会按注册顺序依次执行所有被合并的方法,并返回最后一个方法的返回值。需要注意的是,如果这些方法有返回值且非void,只有最后一个方法的返回值会被获取,前面的返回值会被忽略;此外,若中间任何方法抛出异常,后续方法将不再执行。

Delegate.Combine()如何组合不同签名的委托
使用Delegate.Combine()可以动态地将任意数量的委托实例连接在一起,只要它们的签名一致。该方法接受一个Delegate[]数组作为参数,返回一个新的Delegate对象。这个新对象内部维护了一个委托链表,调用时会遍历链表执行每个目标方法。

using System;
public class Program
{
public delegate void MyDelegate(string msg);
public static void Method1(string msg)
{
Console.WriteLine($"Method1: {msg}");
}
public static void Method2(string msg)
{
Console.WriteLine($"Method2: {msg}");
}
public static void Main()
{
// 创建两个独立的委托实例
MyDelegate d1 = new MyDelegate(Method1);
MyDelegate d2 = new MyDelegate(Method2);
// 使用 Combine 合并
MyDelegate combined = (MyDelegate)Delegate.Combine(d1, d2);
// 调用多播委托
combined("Hello World");
}
}
预期输出: Method1: Hello World Method2: Hello World
使用+和-运算符管理多播委托列表
除了Combine,C#提供了更直观的+和-运算符来添加或移除委托。d1 + d2等价于Delegate.Combine(d1, d2),而d1 - d2则从链表中移除第一个匹配的d2实例。这种操作不会修改原始委托实例,而是生成新的委托对象。这在事件处理场景中非常有用,因为事件本质上是多播委托的封装,外部只能使用+=和-=进行订阅和取消订阅。

using System;
public class Program
{
public delegate void MyDelegate();
public static void MethodA()
{
Console.WriteLine("MethodA");
}
public static void MethodB()
{
Console.WriteLine("MethodB");
}
public static void Main()
{
MyDelegate list = null;
// 添加委托
list += new MyDelegate(MethodA);
list += new MyDelegate(MethodB);
// 移除 MethodA
list -= new MyDelegate(MethodA);
// 此时只执行 MethodB
if (list != null)
{
list();
}
}
}
预期输出: MethodB
多播委托中异常对后续方法执行的影响
当多播委托中的某个方法抛出未捕获异常时,整个调用链会立即中断,后续注册的方法将不会被执行。这是开发者在合并方法时必须考虑的关键行为。为了确保所有方法都能执行,或者为了收集所有方法的返回值,需要手动遍历多播委托的目标列表(通过GetInvocationList())并分别调用,同时包裹在try-catch块中以隔离异常。
using System;
public class Program
{
public delegate int MyDelegate();
public static int FailMethod()
{
throw new Exception("Error in FailMethod");
}
public static int SuccessMethod()
{
return 42;
}
public static void Main()
{
MyDelegate d1 = new MyDelegate(FailMethod);
MyDelegate d2 = new MyDelegate(SuccessMethod);
MyDelegate combined = d1 + d2;
try
{
// 直接调用会因d1抛出异常而中断,d2不会执行
int result = combined();
}
catch (Exception ex)
{
Console.WriteLine($"Caught: {ex.Message}");
}
// 安全调用方式
foreach (MyDelegate del in combined.GetInvocationList())
{
try
{
int res = del();
Console.WriteLine($"Result: {res}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed in {del.Method.Name}: {ex.Message}");
}
}
}
}


















