我知道 += 运算符会将一个方法添加到由 Delegate 基础对象维护的调用列表中,例如
using System;
class Program
{
delegate void MyDelegate(int n);
void Foo(int n)
{
Console.WriteLine("n = {0}", n)
}
static void Main(string[] args)
{
MyDelegate d = new MyDelegate(Foo);
d += Foo; // add Foo again
d.Invoke(3); // Foo is invoked twice as Foo appears two times in invocation list
}
}
但是当我查看 MSDN Delegate , MulticastDelegate我找不到 += 运算符的任何定义。它是如何工作的?自动生成的编译器魔法?
最佳答案
在 IL 术语中,它不是委托(delegate)类型本身的运算符 - 它在语言规范中定义,但您不会使用反射找到它。编译器将其转换为对 Delegate.Combine
的调用.反向操作,使用-
或-=
,使用Delegate.Remove
.
至少,当 C# 以 .NET 为目标时,它是如何实现的,几乎总是如此。理论上,这是特定于环境的——语言规范不要求编译器使用 Delegate.Combine
或 Delegate.Remove
,不同的环境可能没有这些方法。
来自 C# 5 规范,第 7.8.4 节(添加):
The binary
+
operator performs delegate combination when both operands are of some delegate typeD
. (If the operands have different delegate types, a binding-time error occurs.) If the first operand isnull
, the result of the operation is the value of the second operand (even if that is alsonull
). Otherwise, if the second operand isnull
, then the result of the operation is the value of the first operand. Otherwise, the result of the operation is a new delegate instance that, when invoked, invokes the first operand and then invokes the second operand. For examples of delegate combination, see §7.8.5 and §15.4. SinceSystem.Delegate
is not a delegate type, operator+
is not defined for it.
关于c# - += 委托(delegate)运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964927/