拿到的是最后一个被调用的委托实例的返回值。多播委托(multicastdelegate)在调用时,会按照注册顺序依次执行所有注册的委托方法,并丢弃中间过程的返回值,最终将列表末尾那个方法的返回结果作为整个多播委托调用的返回值。

Invoke 的执行顺序是怎样的
执行顺序严格遵循委托链中节点的添加顺序,即先注册的先执行,后注册的后执行。这种顺序是确定的,但需要注意,如果委托链中包含异常,后续的委托可能不会执行。

using System;
public class Program
{
public delegate int MathOp(int a, int b);
public static void Main()
{
MathOp op = null;
// 注册第一个委托:加法
op += (a, b) => { Console.WriteLine("Add"); return a + b; };
// 注册第二个委托:减法
op += (a, b) => { Console.WriteLine("Sub"); return a - b; };
// 注册第三个委托:乘法
op += (a, b) => { Console.WriteLine("Mul"); return a * b; };
// 调用多播委托
int result = op(10, 5);
// 输出结果
Console.WriteLine($"Result: {result}");
}
}
预期输出:
Add Sub Mul Result: 50
在这个例子中,加法返回 15,减法返回 5,乘法返回 50。最终 result 的值是 50,即最后一个执行的委托的返回值。
发生异常时会怎样处理后续委托
如果在执行过程中某个委托抛出异常,且未被捕获,则后续的委托将不会被执行,异常会向上传播。这意味着只有当前异常发生前的委托返回值可能被忽略,而异常后的委托根本不会运行。

using System;
public class Program
{
public delegate int MathOp(int a, int b);
public static void Main()
{
MathOp op = null;
op += (a, b) => { Console.WriteLine("Step 1"); return a + b; };
// 这个委托会抛出异常
op += (a, b) => { throw new Exception("Error in Step 2"); };
op += (a, b) => { Console.WriteLine("Step 3"); return a * b; };
try
{
int result = op(10, 5);
Console.WriteLine($"Result: {result}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
}
预期输出:
Step 1 Exception: Error in Step 2
可以看到,Step 3 没有被打印,说明第三个委托没有执行。异常在第二个委托处中断了执行链。
如何获取所有委托的返回值
如果需要获取所有委托的返回值,不能直接通过多播委托的 Invoke 方法,因为该方法只返回最后一个值。正确的做法是使用 GetInvocationList() 方法获取委托链中的每个独立委托,然后手动遍历并调用它们,从而收集所有返回值。
using System;
using System.Collections.Generic;
public class Program
{
public delegate int MathOp(int a, int b);
public static void Main()
{
MathOp op = null;
op += (a, b) => { Console.WriteLine("Add"); return a + b; };
op += (a, b) => { Console.WriteLine("Sub"); return a - b; };
op += (a, b) => { Console.WriteLine("Mul"); return a * b; };
List<int> results = new List<int>();
// 获取所有委托实例
foreach (MathOp singleCast in op.GetInvocationList())
{
try
{
// 单独调用每个委托
int res = singleCast.Invoke(10, 5);
results.Add(res);
}
catch (Exception ex)
{
Console.WriteLine($"Error in delegate: {ex.Message}");
}
}
Console.WriteLine($"All Results: [{string.Join(", ", results)}]");
}
}
预期输出:
Add Sub Mul All Results: [15, 5, 50]
通过这种方式,我们可以获得所有委托的执行结果,而不是仅仅最后一个。这在需要聚合多个操作结果的场景中非常有用。


















