Why don't I see the += operator overloaded on System.Delegate?

前端 未结 4 1247
心在旅途
心在旅途 2021-01-12 19:03

I see the equality comparison operators == and != overloaded on System.Delegate and MulticastDelegate but not the +

相关标签:
4条回答
  • 2021-01-12 19:09

    The += operator is inferred from the + operator.

    See += Operator (C# Reference)

    0 讨论(0)
  • 2021-01-12 19:22

    The addition operator and the compound assignment(+=) operator of delegates are both built-in supported by the c# compiler.As the 'C# Language Specification' says:

    Delegate combination. Every delegate type implicitly provides the following predefined operator, where D is the delegate type: D operator +(D x, D y); 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.

    0 讨论(0)
  • 2021-01-12 19:32

    The C# compiler translates += operator to the call of the static method Delegate.Combine.

    There are several cases when the compiler does such things, f.e. the + operator of the System.String is compiled to the String.Concat call. Therefore there isn't op_Add method in System.String.

    0 讨论(0)
  • 2021-01-12 19:33

    When you declare a delegate as an event, it is actually an event wrapper around the delegate. See https://stackoverflow.com/a/4893006/397807 for the details. In short, you can only add a handler with += and remove with -= and compiler will help translate it to proper function call.

    0 讨论(0)
提交回复
热议问题