使用 getinvocationlist() 方法获取多播委托内部的独立委托列表,然后遍历该列表并逐个调用,即可收集每个方法的返回结果。这样做可以将原本被后续返回值覆盖的调用链拆解为独立的执行单元,从而分别处理每个订阅者的输出。

GetInvocationList() 如何拆分多播委托
通过 GetInvocationList() 可以安全地获取组成多播委托的所有单个委托实例。默认情况下,多播委托按顺序执行,但只有最后一个方法的返回值会被外部捕获,前面的返回值会丢失。拆分后,我们可以对每个委托进行单独调用,从而保留所有中间结果。

using System;
public class Program
{
public delegate int MathOp(int x);
public static void Main()
{
MathOp op = null;
op += Square;
op += Cube;
op += Double;
int input = 5;
var results = new System.Collections.Generic.List<int>();
foreach (MathOp singleDelegate in op.GetInvocationList())
{
// 注意:Invoke 需要传入正确的参数
results.Add(singleDelegate.Invoke(input));
}
Console.WriteLine(string.Join(", ", results));
}
public static int Square(int x) => x * x;
public static int Cube(int x) => x * x * x;
public static int Double(int x) => x * 2;
}</int>
如何处理多播委托中的异常
在逐个调用的过程中,如果某个订阅者抛出异常,默认的同步多播委托行为会中断后续执行。通过 GetInvocationList() 遍历,我们可以使用 try-catch 块包裹每个单独的调用,确保即使一个方法失败,其他方法仍能继续执行并收集结果。

using System;
public class Program
{
public delegate void ActionWithResult(out string result);
public static void Main()
{
ActionWithResult action = null;
action += SuccessMethod;
action += FailMethod;
action += AnotherSuccess;
var outcomes = new System.Collections.Generic.List<string>();
foreach (ActionWithResult single in action.GetInvocationList())
{
try
{
string res;
single.Invoke(out res);
outcomes.Add(res);
}
catch (Exception ex)
{
outcomes.Add($"Error: {ex.Message}");
}
}
Console.WriteLine(string.Join(" | ", outcomes));
}
public static void SuccessMethod(out string result) => result = "OK_1";
public static void FailMethod(out string result) { throw new Exception("Boom"); }
public static void AnotherSuccess(out string result) => result = "OK_2";
}</string>
当委托返回值为 void 时如何收集状态
如果多播委托签名是 void,则无法直接通过返回值收集数据。此时应改用 out 参数或修改委托签名以支持返回值。若必须保持 void 签名,可以通过在委托内部修改共享状态(如静态字段或类成员变量)来间接收集结果,但这会降低代码的可测试性和线程安全性。










