C#: Inheritance Problem with List

前端 未结 4 1887
面向向阳花
面向向阳花 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:39

    You need to declare your 'Add' method as a 'new' (replacement) method. Try this:

    public class LimitedList : List
    {
        private int _maxitems = 500;
    
        public new void Add(T value) /* Adding a new Value to the buffer */
        {
            base.Add(value);
            TrimData(); /* Delete old data if length too long */
        }
    
        private void TrimData()
        {
            int num = Math.Max(0, base.Count - _maxitems);
            base.RemoveRange(0, num);
        }
    }
    

    notice the 'new' keyword in the 'Add(...' declaration.

    Although, in this instance, you should create your own generic class implementing the IList interface. Hope that helps.

提交回复
热议问题