2011-05-07 48 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如何通過引用計數來進行垃圾回收。對於這樣一個簡單的問題,這不是必需的,但它從長遠來看應該可以幫助你。