如何:使用泛型类 (Visual Basic)How to: Use a Generic Class (Visual Basic)

采用 类型参数 的类称为 泛型类A class that takes type parameters is called a generic class. 如果使用一个泛型类,则可以通过为每个形参提供 类型实参 ,从该类生成 构造类If you are using a generic class, you can generate a constructed class from it by supplying a type argument for each of these parameters. 随后可以声明构造类类型的一个变量,可以创建构造类的实例并将它分配给该变量。You can then declare a variable of the constructed class type, and you can create an instance of the constructed class and assign it to that variable.

除了类之外,你还可以定义和使用泛型结构、接口、过程和委托。In addition to classes, you can also define and use generic structures, interfaces, procedures, and delegates.

下面的过程使用在 .NET Framework 中定义的泛型类,并从它创建一个实例。The following procedure takes a generic class defined in the .NET Framework and creates an instance from it.

使用采用类型参数的类To use a class that takes a type parameter

  1. 在源文件的开头,将 Imports 语句 ( .Net 命名空间,并键入) 以导入 System.Collections.Generic 命名空间。At the beginning of your source file, include an Imports Statement (.NET Namespace and Type) to import the System.Collections.Generic namespace. 这使你可以引用 System.Collections.Generic.Queue<T> 类,而不必完全限定它即可将它与其他队列类(如 System.Collections.Queue)区分开来。This allows you to refer to the System.Collections.Generic.Queue<T> class without having to fully qualify it to differentiate it from other queue classes such as System.Collections.Queue.

  2. 以正常方式创建对象,但是紧接在类名之后添加 (Of type)Create the object in the normal way, but add (Of type) immediately after the class name.

    下面的示例使用相同类 (System.Collections.Generic.Queue<T>) 创建保存不同数据类型的项的两个队列对象。The following example uses the same class (System.Collections.Generic.Queue<T>) to create two queue objects that hold items of different data types. 它将项添加到每个队列末尾,然后从每个队列的前面删除并显示项。It adds items to the end of each queue and then removes and displays items from the front of each queue.

    Public Sub usequeue()
      Dim queueDouble As New System.Collections.Generic.Queue(Of Double)
      Dim queueString As New System.Collections.Generic.Queue(Of String)
      queueDouble.Enqueue(1.1)
      queueDouble.Enqueue(2.2)
      queueDouble.Enqueue(3.3)
      queueDouble.Enqueue(4.4)
      queueString.Enqueue("First string of three")
      queueString.Enqueue("Second string of three")
      queueString.Enqueue("Third string of three")
      Dim s As String = "Queue of Double items (reported length " &
          CStr(queueDouble.Count) & "):"
      For i As Integer = 1 To queueDouble.Count
        s &= vbCrLf & CStr(queueDouble.Dequeue())
      Next i
      s &= vbCrLf & "Queue of String items (reported length " &
          CStr(queueString.Count) & "):"
      For i As Integer = 1 To queueString.Count
        s &= vbCrLf & queueString.Dequeue()
      Next i
      MsgBox(s)
    End Sub
    

请参阅See also