我试图限制我的通用列表的大小,以便在它包含一定数量的值之后,它不会再添加。
我正在尝试使用 List 对象的容量属性来执行此操作,但这似乎不起作用。
Dim slotDates As New List(Of Date)
slotDates.Capacity = 7
人们会如何建议限制列表的大小?
我试图避免在添加每个对象后检查列表的大小。
没有内置方法来限制 List(Of T) 的大小。容量属性只是修改底层缓冲区的大小,而不是限制它。
如果你想限制列表的大小,你需要创建一个检查无效大小的包装器。例如
Public Class RestrictedList(Of T)
Private _list as New List(Of T)
Private _limit as Integer
Public Property Limit As Integer
Get
return _limit
End Get
Set
_limit = Value
End Set
End Property
Public Sub Add(T value)
if _list.Count = _limit Then
Throw New InvalidOperationException("List at limit")
End If
_list.Add(value)
End Sub
End Class
有几种不同的方法可以向 a 中添加内容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
这样,无论您Add
还是Insert
.
您需要派生一个新的LimitedList
并隐藏添加方法。这样的事情会让你开始。
public class LimitedList<T> : List<T>
{
private int limit;
public LimitedList(int limit)
{
this.limit = limit;
}
public new void Add(T item)
{
if (Count < limit)
base.Add(item);
}
}
刚意识到你在VB,我会尽快翻译
编辑请参阅 Jared 的 VB 版本。我会把它留在这里,以防有人想要一个 C# 版本开始使用。
对于它的价值,我采取了一种稍微不同的方法,因为它扩展了 List 类而不是封装它。您要使用哪种方法取决于您的情况。
如果您需要限制其中项目的最大数量,您应该实现自己的列表/集合。