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

后端 未结 5 1891
無奈伤痛
無奈伤痛 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:17

    There are several different ways to add things to a List: Add, AddRange, Insert, etc.

    Consider a solution that inherits from Collection:

    Public Class LimitedCollection(Of T)
        Inherits System.Collections.ObjectModel.Collection(Of T)
    
        Private _Capacity As Integer
        Public Property Capacity() As Integer
            Get
                Return _Capacity
            End Get
            Set(ByVal value As Integer)
                _Capacity = value
            End Set
        End Property
    
        Protected Overrides Sub InsertItem(ByVal index As Integer, ByVal item As T)
            If Me.Count = Capacity Then
                Dim message As String = 
                    String.Format("List cannot hold more than {0} items", Capacity)
                Throw New InvalidOperationException(message)
            End If
            MyBase.InsertItem(index, item)
        End Sub
    
    End Class
    

    This way the capacity is respected whether you Add or Insert.

提交回复
热议问题