【问题标题】:c# collection with automatic item removal [duplicate]带有自动删除项目的 c# 集合
【发布时间】:2011-08-20 21:08:43
【问题描述】:

可能重复:
Fixed size queue which automatically dequeues old values upon new enques

有没有像集合这样的东西,当添加新项目时会自动删除旧项目?假设我有一个限制为十项的列表。添加第 11 个项目后,第一个被删除,容量保持在 10 个。好像会有这样的东西,但我找不到。有什么想法吗?

【问题讨论】:

    标签: c# collections


    【解决方案1】:

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

    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
            }
        }
    }
    

    【讨论】:

    • 是的,自定义编码是我做的第一件事,但后来我想............
    【解决方案2】:

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

    //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);
            }
        }
    

    【讨论】:

      【解决方案3】:

      AFIK,这样的集合不存在。你将不得不自己动手。一种可能性是从ObservableCollection&lt;T&gt; 派生并使用CollectionChanged 事件删除“旧”项目

      【讨论】:

        【解决方案4】:

        以上答案都是正确的;您必须编写自己的代码。

        但是,您可以使用引用计数来实现这一点。 link 说明 .NET 如何通过引用计数进行垃圾收集。对于这样一个简单的问题,这不是必需的,但从长远来看,它可能会对您有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-11
          • 1970-01-01
          • 2021-04-02
          • 1970-01-01
          • 1970-01-01
          • 2019-07-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多