合并代表

Combining delegates

代码如下

Func<int, int> DoWork;
DoWork = x => x + 5;  // ignored
DoWork += y => y + 1; // used
Console.WriteLine(DoWork(2)); // 2 + 1 = 3

returns 3,因为只处理最新添加的lambda——前面的方法被忽略了。在 Action<> 的情况下,正在处理所有方法。

问题: "adding"/ Delegate.Combine Funcs 是否有一个用例,每次我添加另一个委托时,以前的函数都会被覆盖?

"previous ones" 不会被覆盖。它们都将被调用,但只有最后一个的 return 值被 returned。

C# 规范(15.4 委托调用)对其进行了解释:

If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.


要对其进行测试,请尝试以下操作:

DoWork = x => { Console.WriteLine(x + 5); return x + 5; };
DoWork += y => { Console.WriteLine(y + 1); return y + 1; };

Console.WriteLine(DoWork(2)); // 2 + 1 = 3

它将打印

7
3
3

最常见的用例可能是使用多个事件处理程序订阅同一事件。