在EventHandler中使用foreach迭代器值
这个问题在这里已经有了答案:
如果您想使用多个匿名事件处理程序,并且以后仍可以将其分离,则可以将分离操作简单地存储在单独的列表中,如下所示:
// these actions should be invoked during cleanup
private readonly List<Action> _cleanupActions = new List<Action>();
public void Start()
{
foreach (var m in mappings)
{
// you need both closures in order to reference them inside
// the cleanup action
var mapping = m;
PropertyChangedEventHandler handler = (s, e) => { /* ... */ };
// attach now
mapping.PropertyChanged += handler;
// add a cleanup action to detach later
_cleanupActions.Add(() => mapping.PropertyChanged -= handler);
}
public void Stop()
{
// invoke all cleanup actions
foreach (var action in _cleanupActions)
action();
}
这很简洁,因为它允许任意复杂的清理操作,并捕获正确的对象及其事件处理程序。
链接地址: http://www.djcxy.com/p/51437.html