Limit the size of a generic collection?

后端 未结 4 975
野的像风
野的像风 2020-12-31 18:20

Is there any way to limit the size of a generic collection?

I have a Stack of WriteableBitmap which I am using to store a clone of a WriteableBitmap on each change,

相关标签:
4条回答
  • 2020-12-31 18:41

    You will have to check the size (You will get an exception I believe if you set a limit, and don't check if it's full).

    Edit

    You don't get an exception if the size has been set, but the size just increases so you do have to check the size (via http://msdn.microsoft.com/en-us/library/6335ax0f.aspx):-

    If Count already equals the capacity, the capacity of the Stack is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added.

    0 讨论(0)
  • 2020-12-31 18:53

    To elaborate on Tilak's answer here is some example code:

      public class LimitedSizeStack<T> : LinkedList<T>
      {
        private readonly int _maxSize;
        public LimitedSizeStack(int maxSize)
        {
          _maxSize = maxSize;
        }
    
        public void Push(T item)
        {
          this.AddFirst(item);
    
          if(this.Count > _maxSize)
            this.RemoveLast();
        }
    
        public T Pop()
        {
          var item = this.First.Value;
          this.RemoveFirst();
          return item;
        }
      }
    
    0 讨论(0)
  • 2020-12-31 18:57

    You can use LinkedList which represents doubly link list to simulate Circular Stack.

    You can you AddFirst() corresponding to Push(). If Count is 10, you can use RemoveLast().

    For Pop() you can use RemoveFirst()

    0 讨论(0)
  • 2020-12-31 18:58

    You have to implement your own wrapper to achieve that. There is no direct option available.

    class FixedSizeStack : Stack
    {
        private int MaxNumber;
        public FixedSizeStack(int Limit)
            : base()
        {
            MaxNumber = Limit;
        }
    
        public override void Push(object obj)
        {
            if (this.Count < MaxNumber)
                base.Push(obj);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题