HOW TO:使用泛型類別 (Visual Basic)How to: Use a Generic Class (Visual Basic)

採用 「類型參數」 (type parameter) 的類別稱為 「泛型類別」(generic class)。A class that takes type parameters is called a generic class. 如果您使用泛型類別,則可以透過它產生 「建構類別」 (constructed class),方法是提供所有這些參數的 「類型引數」 (type argument)。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)
      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
    End Sub

另請參閱See also