+ =为运营商代表 [英] += operator for Delegate
问题描述
我知道,在 + = 运营商将一个方法添加到由代表基本对象保持调用列表,例如:
I know that the += operator will add a method to the invocation list maintained by the Delegate base object, for example
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 代表 MulticastDelegate 我找不到任何在 + = 运算符的定义。它是如何,这只是工作的?自动生成的编译器魔术
But when I look at MSDN Delegate, MulticastDelegate I can't find any definition of the += operator. How is it that is just works? Auto-generated compiler magic?
推荐答案
这不是在委托类型本身的运营商,在IL方面 - 它在语言定义规范,但你不会使用反射找到它。编译器把它变成一个电话 Delegate.Combine
一>。反向操作,使用 -
或 - =
,使用的 Delegate.Remove
。
It's not an operator on the delegate type itself, in IL terms - it's defined in the language specification, but you wouldn't find it using reflection. The compiler turns it into a call to Delegate.Combine
. The reverse operation, using -
or -=
, uses Delegate.Remove
.
至少,这是它是如何实现的。当C#.NET的目标,因为它几乎总是这样。从理论上讲,这是环境特定的 - 语言规范并不要求编译器使用 Delegate.Combine
或 Delegate.Remove $ C 。$ C>,和不同的环境中可能不具有这些方法
At least, that's how it's implemented when C# targets .NET, as it almost always does. In theory, this is environment-specific - the language specification doesn't require that a compiler uses Delegate.Combine
or Delegate.Remove
, and a different environment may not have those methods.
从C#5说明书中,部分7.8.4(加法):
From the C# 5 specification, section 7.8.4 (addition):
二进制 +
运算符执行委托组合当两个操作数是一些委托类型 d的
。 (如果操作数具有不同的委托类型,则发生绑定时错误)。如果第一个操作数是空
,操作的结果是第二个操作数的值(即使那也是空
)。否则,如果第二操作数是空
,则操作的结果是所述第一操作数的值。否则,操作的结果是一个新委托实例,被调用时调用第一个操作数,然后调用第二个操作数。对于委托组合的示例,请参见§7.8.5和§15.4。由于 System.Delegate
不是委托类型,运营商 +
没有为它定义。
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.
这篇关于+ =为运营商代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!