代码之家  ›  专栏  ›  技术社区  ›  SqlRyan

VB.NET强类型集合

  •  10
  • SqlRyan  · 技术社区  · 17 年前

    我想在VB.NET中创建一个集合,但我只希望它接受特定类型的对象。例如,我想创建一个名为“FooCollection”的类,它在各方面都像集合一样,但只接受“Foo”类型的对象。

    我想我可以使用泛型,使用以下语法来实现这一点:

        Public Class FooCollection(Of type As Foo)
            Inherits CollectionBase
    
            ...
    
        End Class
    

    但我在编译它时遇到了一个错误,我“必须实现一个默认的访问器”,所以很明显缺少了一些东西。我不想在实例化时指定它接受的类型——我希望FooCollection本身指定它只接受Foo对象。我在C#中看到过用强类型列表完成它,所以也许我所寻找的只是VB.NET语法。

    谢谢你的帮助!

    编辑:谢谢你的回答。这就可以了,但我想以某种方式命名类类型,我实际上用以下代码完成了我想要的东西:

    Public Class FooCollection
        Inherits List(Of Foo)
    
    End Class
    
    2 回复  |  直到 17 年前
        1
  •  10
  •   Andrew Moore    17 年前

    你为什么不直接用 List(Of Foo) …它已经在VB.NET下 System.Collections.Generic .要使用,只需声明如下:

    Private myList As New List(Of Foo) 'Creates a Foo List'
    Private myIntList As New List(Of Integer) 'Creates an Integer List'
    

    看见 MSDN > List(T) Class (System.Collections.Generic) 了解更多信息。

        2
  •  1
  •   Jeff Cope    15 年前

    您需要为集合实现一个默认属性,如下所示:

    Default Public Property Item(ByVal Index As Integer) As Foo
    Get
      Return CType(List.Item(Index), Foo)
    End Get
    Set(ByVal Value As Foo)
      List.Item(Index) = Value
    End Set
    

    结束财产