c# - += 委托(delegate)运算符

标签 c# delegates

我知道 += 运算符会将一个方法添加到由 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.CombineDelegate.Remove,不同的环境可能没有这些方法。

来自 C# 5 规范,第 7.8.4 节(添加):

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.

关于c# - += 委托(delegate)运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964927/

相关文章:

c# - 带有种子的添加迁移抛出 "no value provided"异常

c# - 如何设置读取xml文件的起点?

asp.net - 我可以获得有关 JavaScript 委托(delegate)的一些建议吗?

ios - 为什么一个简单的模态视图 Controller 在呈现和关闭时会滞后?

c# - 在 C# 对象上调用 C++/CLI delete

c# - 捕获另一个进程未处理的异常

c# - 调用函数的最佳方式是什么?

c# - 最佳实践 : When should I use a delegate in . NET?

iphone - 调用协议(protocol)方法是否通过程序流控制?

c# - 如何忽略 asp.net 中的路由表单 url 路由