gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:29:46 26 4
gpt4 key购买 nike

我知道 += 运算符会将一个方法添加到由 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com