问题描述
我正在寻找 Stack
和 Queue
的 INotifyCollectionChanged
实现.我可以自己动手,但我不想重新发明轮子.
I'm looking for an INotifyCollectionChanged
implementation of Stack
and Queue
. I could roll my own but I don't want to reinvent the wheel.
推荐答案
使用堆栈和队列(几乎按照定义),您只能访问堆栈顶部或队列头部.这就是它们与 List
的区别所在.(所以,这就是你没有找到的原因)
With Stacks and Queues (almost by definition) you only have access to the top of the stack or head of the queue. It's what differentiates them from a List
. (and so, that's why you haven't found one)
虽然您可以编写自己的答案,但我会通过从 ObservableCollection
派生来回答,然后在将 Push
实现为 的堆栈的情况下在偏移量 0 处插入
(并作为返回索引 0 弹出,然后 RemoveAt
索引 0);或者使用队列,您可以将 Add
到列表的末尾以 Enqueue
,然后像堆栈一样为 Dequeue 抓取并删除第一项代码>.
Insert
、Add
和 RemoveAt
操作将在底层 ObservableCollection
上调用,因此会导致 CollectionChanged
要触发的事件.
To answer though you could write your own, I would do it by deriving from ObservableCollection
, then in the case of a stack implementing the Push
as an Insert
at offset 0 (and pop as returning index 0 then RemoveAt
index 0); or with a queue you could just Add
to the end of the list to Enqueue
, and the grab and remove the first item, as with the stack, for Dequeue
. The Insert
, Add
and RemoveAt
operations would be called on the underlying ObservableCollection
and so cause the CollectionChanged
event to be fired.
您可能还说,您只是想绑定或在您应该有权访问的一项更改时收到通知.您将再次创建自己的类,派生自 Stack 或 Queue,并在以下情况下手动触发 CollectionChanged 事件:
You might also be saying that you simply want to bind or be notified when the one item you are supposed to have access to changes. You would create your own class again, derived from Stack or Queue, and fire the CollectionChanged event manually when:
- 某些东西被压入堆栈或从堆栈中弹出
- 某物从队列中出列
- 当队列之前是空的时,队列中有东西在排队
这篇关于可观察的堆栈和队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!