限制List(Of T)的大小 - VB.NET [英] Limit the size of List(Of T) - VB.NET

查看:190
本文介绍了限制List(Of T)的大小 - VB.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图限制泛型列表的大小,以便在它包含一定数量的值之后,它不会再添加任何值。



我是试图使用List对象的Capacity属性来做到这一点,但这似乎并不奏效。

  Dim slotDates As New List (日期)
slotDates.Capacity = 7

一个列表?

我试图避免在添加每个对象后检查列表的大小。

解决方案

有几种不同的方法可以将其添加到 List< T> :Add,AddRange,Insert等。



考虑从集合< T>



<$ p公共类LimitedCollection(Of T)
继承System.Collections.ObjectModel.Collection(Of T)

私有_Capacity作为整数
公共属性容量()As Integer
Get
返回_Capacity
End
Set(ByVal value As Integer)
_Capacity = value
End Set
End属性

受保护的覆盖Sub InsertItem(ByVal index As Integer,ByVal item As T)
如果Me.Count = Capacity然后
Dim message As String =
String。格式(List不能超过{0}个项目,容量)
抛出新的InvalidOperationException(消息)
结束如果
MyBase.InsertItem(index,item)
End Sub

End Class

无论您是添加插入


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 Capacity property of the List object, but this does not seem to work.

        Dim slotDates As New List(Of Date)
        slotDates.Capacity = 7

How would people advice limiting the size of a list?

I am trying to avoid checking the size of the List after each object is added.

解决方案

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

Consider a solution that inherits from 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

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

这篇关于限制List(Of T)的大小 - VB.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆