C#: Inheritance Problem with List

前端 未结 4 1890
面向向阳花
面向向阳花 2020-12-19 10:55

Let\'s assume this class in C#:

public class LimitedList : List
{
    private int _maxitems = 500;

    public void Add(T value) /* Adding          


        
4条回答
  •  余生分开走
    2020-12-19 11:25

    No - don't use new here; that doesn't give you polymorphism. List isn't intended for inheritance in this way; use Collection and override the Add InsertItem method.

    public class LimitedCollection : Collection
    {
        private int _maxitems = 500;
    
        protected override void InsertItem(int index, T item)
        {
            base.InsertItem(index, item);
            TrimData(); /* Delete old data if lenght too long */
        }
    
        private void TrimData()
        {
            int num = Math.Max(0, base.Count - _maxitems);
            while (num > 0)
            {
                base.RemoveAt(0);
                num--;
            }
        }
    }
    

提交回复
热议问题