2011-05-07 73 views

回答

4

一种可能的方式来实现自己的目标:

public class FixedSizedQueue<T> : Queue<T> 
{ 
    private readonly int maxQueueSize; 
    private readonly object syncRoot = new object(); 

    public FixedSizedQueue(int maxQueueSize) 
    { 
     this.maxQueueSize = maxQueueSize; 
    } 

    public new void Enqueue(T item) 
    { 
     lock (syncRoot) 
     { 
      base.Enqueue(item); 
      if (Count > maxQueueSize) 
       Dequeue(); // Throw away 
     } 
    } 
} 
+0

是的,自定义编码是我做的第一件事,但后来我想知道.......... – 2011-05-07 22:01:15

0

AFIK,这样的集合不存在。你将不得不推出自己的。一种可能性是从ObservableCollection<T>获得并使用CollectionChanged活动,删除“旧”项目

0

您可以通过自定义编码实现这一点,看看

//Lets suppose Customer is your custom class 
    public class CustomerCollection : CollectionBase 
    { 
     public Customer this[int index] 
     { 
      get 
      { 
       return (Customer) this.List[index]; 
      } 
      set 
      { 
       this.List[index] = value; 
      } 
     } 
     public void Add(Customer customer) 
     { 
      if(this.List.Count > 9) 
       this.List.RemoveAt(0);   
      this.List.Add(customer); 
     } 
    } 
0

上述答案是正确的;你必须编写你自己的代码。

但是,您可以使用引用计数来实现此目的。 link说.NET如何通过引用计数来进行垃圾回收。对于这样一个简单的问题,这不是必需的,但它从长远来看应该可以帮助你。