我试图限制我的通用列表的大小,以便在它包含一定数量的值后,它将不再添加.
我试图使用List对象的Capacity属性执行此操作,但这似乎不起作用.
- Dim slotDates As New List(Of Date)
- slotDates.Capacity = 7
人们会如何建议限制列表的大小?
我试图避免在添加每个对象后检查List的大小.
有几种不同的方法可以将内容添加到List< T>:Add,AddRange,Insert等.
考虑一个继承自Collection< T>的解决方案:
- 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
这样,无论您是添加还是插入,都会尊重容量.