+= operator for Delegate

前端 未结 2 1028

I know that the += operator will add a method to the invocation list maintained by the Delegate base object, for example

using System;

clas         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 05:11

    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.

    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.

    From the C# 5 specification, section 7.8.4 (addition):

    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.

提交回复
热议问题