我想知道C#如何解释这段代码。
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)如何翻译? 我想这样的事情:
ChangeStateHandler ev = ChangeStateEvent;
foreach (myHandler in ev) {
myHandler(this, e);
}
但是,单个函数(ev)如何生成循环?如何实现类似的东西?
干杯
答案 0 :(得分:2)
关闭 - 语义类似于:
foreach (ChangeStateHandler myHandler in ev.GetInvocationList()) {
myHandler(this, e);
}