Limit the size of List(Of T) - VB.NET

后端 未结 5 1851
無奈伤痛
無奈伤痛 2021-01-18 06:46

I am trying to limit the size of my generic list so that after it contains a certain amount of values, it won\'t add any more.

I am trying to do this using the Capac

5条回答
  •  天涯浪人
    2021-01-18 07:00

    You'll want to derive a new LimitedList and shadow the adding methods. Something like this will get you started.

    public class LimitedList : List
    {
        private int limit;
    
        public LimitedList(int limit)
        {
            this.limit = limit;
        }
    
        public new void Add(T item)
        {
            if (Count < limit)
                base.Add(item);
        }
    }
    

    Just realised you're in VB, I'll translate shortly

    Edit See Jared's for a VB version. I'll leave this here in case someone wants a C# version to get started with.

    For what it's worth mine takes a slightly different approach as it extends the List class rather than encapsulating it. Which approach you want to use depends on your situation.

提交回复
热议问题