Loop over delegate

2019-08-10 06:55发布

问题:

I want to know how C# interprete that piece of code.

    public delegate void ChangeStateHandler(object sender, EventArgs e);
    public event ChangeStateHandler ChangeStateEvent = delegate { };

    protected void OnChangeState(EventArgs e) {
        ChangeStateHandler ev = ChangeStateEvent;

        ev(this, e);   // <<<<< that LINE
    }

I know that is partial translated to:

private EventHandlerList events = new EventHandlerList();  
    private Object myeventObject = new object();  
    public event EventHandler<EventArgs> myevent  
    {  
        add { events.AddHandler(myeventObject, value); }  
        remove { events.RemoveHandler(myeventObject, value); }  
    }  

In the "reality" ev(this, e) how is translated? I suppose something like:

ChangeStateHandler ev = ChangeStateEvent;
foreach (myHandler in ev) {
     myHandler(this, e);
}

But, how a single function ( ev ) can generate a loop? And how implement something like that?

Cheers

回答1:

Close - it is semantically similar to:

foreach (ChangeStateHandler myHandler in ev.GetInvocationList()) {
     myHandler(this, e);
}