C#: Inheritance Problem with List

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

    You can avoid this warning by adding "new" to the declaration.

    public new void Add(T value) { 
     ...
    }
    

    However I think you may be approaching this problem a bit wrong by using Inheritance. From my perspective LimitedList is not a List because it expresses very different behavior as it puts a hard constraint on the amount of data in the List. I think it would be much better to not inherit from List but have a List as a member variable.

    Another reason why this is a bad idea is that you won't be able to satisfy your class's contract when it is viewed as a List. The following code will use the List`s Add method and not LimitedList.

    List list = new LimitedList(10);
    for ( i = 0; i < 10000; i++ ) {
      list.Add(i);
    }
    

提交回复
热议问题