本文介绍了遍历委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道C#如何解释这段代码.

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
    }

我知道部分翻译为:

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); }  
    }  

在现实" ev(this,e)中如何翻译?我想是这样的:

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

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

但是,单个函数(ev)如何生成循环?以及如何实现类似的东西?

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

欢呼

推荐答案

关闭-语义上类似于:

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

这篇关于遍历委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:55