注意:这更像是一个好奇的问题。
鉴于List<Window>
每个窗口都有一个附加到关闭事件的事件,该事件从集合中删除窗口,您如何使用委托/事件来推迟关闭事件的执行,直到集合被迭代?
例如:
public class Foo
{
private List<Window> OpenedWindows { get; set; }
public Foo()
{
OpenedWindows = new List<Window>();
}
public void AddWindow( Window win )
{
win.Closed += OnWindowClosed;
OpenedWindows.Add( win );
}
void OnWindowClosed( object sender, EventArgs e )
{
var win = sender as Window;
if( win != null )
{
OpenedWindows.Remove( win );
}
}
void CloseAllWindows()
{
// obviously will not work because we can't
// remove items as we iterate the collection
// (the close event removes the window from the collection)
OpenedWindows.ForEach( x => x.Close() );
// works fine, but would like to know how to do
// this with delegates / events.
while( OpenedWindows.Any() )
{
OpenedWindows[0].Close();
}
}
}
具体来说,在该CloseAllWindows()
方法中,如何迭代集合以调用 close 事件,但将引发的事件推迟到集合完全迭代?