限制List(Of T)的大小 - VB.NET

w4y*_*ymo 7 vb.net generics list limit

我试图限制我的通用列表的大小,以便在它包含一定数量的值后,它将不再添加.

我试图使用List对象的Capacity属性执行此操作,但这似乎不起作用.

        Dim slotDates As New List(Of Date)
        slotDates.Capacity = 7
Run Code Online (Sandbox Code Playgroud)

人们如何建议限制列表的大小?

我试图避免在添加每个对象后检查List的大小.

Jar*_*Par 14

没有内置方法来限制List(Of T)的大小.Capacity属性仅修改底层缓冲区的大小,而不是限制它.

如果要限制List的大小,则需要创建一个检查无效大小的包装器.例如

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
Run Code Online (Sandbox Code Playgroud)


Rya*_*ndy 10

有几种不同的方法可以添加东西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
Run Code Online (Sandbox Code Playgroud)

通过这种方式,能得到尊重你是否Add还是Insert.


Gar*_*ler 5

你想要得到一个新的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

刚刚意识到你在VB,我很快就会翻译

编辑请参阅Jared的VB版本.我会留下这个,以防有人想要一个C#版本开始.

对于它的价值,我采用了稍微不同的方法,因为它扩展了List类而不是封装它.您想要使用哪种方法取决于您的情况.