Observable Stack and Queue

后端 未结 4 1928
无人及你
无人及你 2020-11-27 22:34

I\'m looking for an INotifyCollectionChanged implementation of Stack and Queue. I could roll my own but I don\'t want to reinvent the

4条回答
  •  感动是毒
    2020-11-27 22:52

    I realize there are already a few answers but figured I would give back a little with mine. I put together everything mentioned in the posts and comments. There were few things that motivated me to do this:

    • INPC should always fire for Count when Push, Pop, or Clear are called, as mentioned in one of the posts.
    • For Clear, action should be Reset and index for the collection change event should be set to -1 (which it will default to anyway if not set so the other posts have that): .NET docs
    • For Push/Pop, action should be Add/Remove and index for the collection changed event should be 0 for a stack being that it is always and only the first item that can be maniuplated (think stack.GetEnumerator().MoveNext()).
    • Exposed all 3 constructors available in Stack and use base() calls since there is no reason to override the logic.

    Results in:

    public class ObservableStack : Stack, INotifyCollectionChanged, INotifyPropertyChanged
    {
        #region Constructors
    
        public ObservableStack() : base() { }
    
        public ObservableStack(IEnumerable collection) : base(collection) { }
    
        public ObservableStack(int capacity) : base(capacity) { }
    
        #endregion
    
        #region Overrides
    
        public virtual new T Pop()
        {
            var item = base.Pop();
            OnCollectionChanged(NotifyCollectionChangedAction.Remove, item);
    
            return item;
        }
    
        public virtual new void Push(T item)
        {
            base.Push(item);
            OnCollectionChanged(NotifyCollectionChangedAction.Add, item);
        }
    
        public virtual new void Clear()
        {
            base.Clear();
            OnCollectionChanged(NotifyCollectionChangedAction.Reset, default);
        }
    
        #endregion
    
        #region CollectionChanged
    
        public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
    
        protected virtual void OnCollectionChanged(NotifyCollectionChangedAction action, T item)
        {
            CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(
                action
                , item
                , item == null ? -1 : 0)
            );
    
            OnPropertyChanged(nameof(Count));
        }
    
        #endregion
    
        #region PropertyChanged
    
        public virtual event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged(string proertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(proertyName));
        }
    
        #endregion
    }
    

提交回复
热议问题