c# - 可观察的堆栈和队列

标签 c# stack queue inotifycollectionchanged

我正在寻找 StackQueueINotifyCollectionChanged 实现。我可以自己动手,但我不想重新发明轮子。

最佳答案

我遇到了同样的问题,想与其他人分享我的解决方案。希望这对某人有帮助。

public class ObservableStack<T> : Stack<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
    public ObservableStack()
    {
    }

    public ObservableStack(IEnumerable<T> collection)
    {
        foreach (var item in collection)
            base.Push(item);
    }

    public ObservableStack(List<T> list)
    {
        foreach (var item in list)
            base.Push(item);
    }


    public new virtual void Clear()
    {
        base.Clear();
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }

    public new virtual T Pop()
    {
        var item = base.Pop();
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));
        return item;
    }

    public new virtual void Push(T item)
    {
        base.Push(item);
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
    }


    public virtual event NotifyCollectionChangedEventHandler CollectionChanged;


    protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        this.RaiseCollectionChanged(e);
    }

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        this.RaisePropertyChanged(e);
    }


    protected virtual event PropertyChangedEventHandler PropertyChanged;


    private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (this.CollectionChanged != null)
            this.CollectionChanged(this, e);
    }

    private void RaisePropertyChanged(PropertyChangedEventArgs e)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, e);
    }


    event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
    {
        add { this.PropertyChanged += value; }
        remove { this.PropertyChanged -= value; }
    }
}

关于c# - 可观察的堆栈和队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3127136/

相关文章:

r - 制作不同范围的光栅堆栈

java - DFS Java 实现 : how to write "Element in deque/stack"

queue - "enqueue"和 "dequeue"的区别

java - kafka vs 编年史队列 vs 破坏者

c# - id 在数组中时的 linq where 子句

c# - 嵌套分组策略/算法c#

c# - 将数据传递给 Vue.js 组件

c++ - 在堆栈上构造之前的定义?类似于指针

C#队列对象入队后在队列中修改

c# - WPF 数据绑定(bind)以启用基于多个条件的控制