Why do Queue(T) and Stack(T) not implement ICollection(T)?

后端 未结 3 1048
眼角桃花
眼角桃花 2021-02-01 07:54

Before I even ask, let me get the obvious answer out of the way: The ICollection interface includes a Remove method to remove an arbitrary

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 08:16

    Philip has given a good answer (+1). There is another conceptual promise that Remove will break for Stack. The ICollection.Remove is documented as:

    Removes the first occurrence of a specific object from the ICollection.

    Stack is LIFO, even if Remove was implemented, it will have to remove the last occurrence in case of duplicate objects.

    If it doesnt make sense for Stack, it's better avoidable for its equal and opposite cousin.


    I would have liked it better if MS:

    • didn't document Remove for ICollection like that. Deleting an equal object somewhere would have made more sense considering how vastly different the internal implementations of various structures are. Forcing the removal of first item looks like influenced from linear searching of simple structures like arrays.

    • had interfaces for queue structures. May be:

      public interface IPeekable : IEnumerable // or IInOut or similar
      {
          int Count { get; }
      
          bool Contains(T item);
          T Peek();
          void Add(T item);
          bool Remove();
          void Clear();
      }
      

提交回复
热议问题