Unsubscribe from an event of a general class whose type parameter is specified in the general method

How to unsubscribe from an event of a general class whose type parameter is specified in the general method as follows:

public class ListLayoutControl : Control
{
    NotifyCollectionChangedEventHandler handler = null;

    public void AttachTo<T, U>(T list) where T : INotifyCollectionChanged, ICollection<U>
    {
        handler = delegate (object sender, NotifyCollectionChangedEventArgs e)
        {
            UpdateLayout(list.Count);
        };
        list.CollectionChanged += handler;
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            // unsubscribe ??
        }
        base.Dispose(disposing);
    }
}
+4
source share
1 answer

Block unsubscribe in a separate deletion and execute it at the disposal of:

private Action _unsubscribeHandler;
public void AttachTo<T, U>(T list) where T : INotifyCollectionChanged, ICollection<U>
{
    NotifyCollectionChangedEventHandler handler = delegate (object sender, NotifyCollectionChangedEventArgs e)
    {
        UpdateLayout(list.Count);
    };
    list.CollectionChanged += handler;
    _unsubscribeHandler = () => {
        list.CollectionChanged -= handler;     
    };
}

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        _unsubscribeHandler?.Invoke();
    }
    base.Dispose(disposing);
}

If you can call AttachToseveral times with different lists, collect the unsubscribe handlers in List<Action>and execute all of them.

+4
source

Source: https://habr.com/ru/post/1695707/


All Articles