+= 代表操作符

+= operator for Delegate(+= 代表操作符)

本文介绍了+= 代表操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道+=操作符会在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 Delegate 时,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.CombineDelegate.Remove,不同的环境可能没有这些方法.

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 时执行委托组合.(如果操作数具有不同的委托类型,则会发生绑定时错误.)如果第一个操作数是 null,则操作的结果是第二个操作数的值(即使那也是 <代码>空).否则,如果第二个操作数为 null,则运算结果为第一个操作数的值.否则,操作的结果是一个新的委托实例,当被调用时,它会调用第一个操作数,然后调用第二个操作数.有关委托组合的示例,请参见 §7.8.5 和 §15.4.由于 System.Delegate 不是委托类型,因此没有为它定义运算符 +.

The binary + operator performs delegate combination when both operands are of some delegate type D. (If the operands have different delegate types, a binding-time error occurs.) If the first operand is null, the result of the operation is the value of the second operand (even if that is also null). Otherwise, if the second operand is null, 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. Since System.Delegate is not a delegate type, operator + is not defined for it.

这篇关于+= 代表操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:+= 代表操作符

基础教程推荐