Using foreach iterator value inside EventHandler

This question already has an answer here:

  • Unsubscribe anonymous method in C# 11 answers
  • How to remove a lambda event handler [duplicate] 1 answer

  • If you want to use multiple anonymous event handlers and still be able to detach them later, you can simply store detach actions in a separate list, similar to:

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

    This is neat as it allows cleanup actions of arbitrary complexity, and it captures correct pairs of objects and their event handlers.

    链接地址: http://www.djcxy.com/p/51438.html

    上一篇: 通过匿名代理进行事件取消订阅

    下一篇: 在EventHandler中使用foreach迭代器值