【发布时间】:2011-08-20 21:08:43
【问题描述】:
可能重复:
Fixed size queue which automatically dequeues old values upon new enques
有没有像集合这样的东西,当添加新项目时会自动删除旧项目?假设我有一个限制为十项的列表。添加第 11 个项目后,第一个被删除,容量保持在 10 个。好像会有这样的东西,但我找不到。有什么想法吗?
【问题讨论】:
标签: c# collections
可能重复:
Fixed size queue which automatically dequeues old values upon new enques
有没有像集合这样的东西,当添加新项目时会自动删除旧项目?假设我有一个限制为十项的列表。添加第 11 个项目后,第一个被删除,容量保持在 10 个。好像会有这样的东西,但我找不到。有什么想法吗?
【问题讨论】:
标签: c# collections
实现目标的一种可能方式:
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
}
}
}
【讨论】:
您可以通过自定义编码来实现这一点,看看
//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);
}
}
【讨论】:
AFIK,这样的集合不存在。你将不得不自己动手。一种可能性是从ObservableCollection<T> 派生并使用CollectionChanged 事件删除“旧”项目
【讨论】:
以上答案都是正确的;您必须编写自己的代码。
但是,您可以使用引用计数来实现这一点。 link 说明 .NET 如何通过引用计数进行垃圾收集。对于这样一个简单的问题,这不是必需的,但从长远来看,它可能会对您有所帮助。
【讨论】: