Multicast delegate weird behavior in C#?

前端 未结 4 1066
春和景丽
春和景丽 2020-12-10 23:57

I have this simple event :

public class ClassA
{
    public event Func Ev;
    public int Do(string l)
    {
        return Ev(l);
    }
}
         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 00:09

    There are three aspects at play here:

    1. The implementation of the event
    2. The behaviour of delegate combination
    3. The behaviour of invoking a delegate whose invocation list has multiple entries

    For point 1, you have a field-like event. Section 10.8.1 of the C# 4 spec gives an example, and states that:

    Outside the declaration of the Button class, the Click member can be used only on the left-hand saide of the += and -= operators, as in

    b.Click += new EventHandler(...);
    

    which appends a delegate to the invocation list of the Click event

    (emphasis mine). The spec also makes it clear that a field-like event creates a delegate field, which is used from within the class for invocation.

    More generally (point 2), section 7.8.4 of the C# 4 spec talks about delegate combination via + and +=:

    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 + operato performs delegate combination when both operands are of some delegate type D. [... skip bits where x or y are null ...] Otherwise, the result of the operation is a new delegate that, when invoked, invokes the first operand and then invokes the second operand.

    (Again, emphasis mine.)

    Finally, point 3 - event invocation and return values. Section 15.4 of the C# spec states:

    If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.

    More generally, it depends on the event implementation. If you use an event implementation which uses the "normal" delegate combination/removal steps, everything is guaranteed. If you start writing a custom implementation which does crazy things, that's a different matter.

提交回复
热议问题