แก้ไข

แชร์ผ่าน


How to: Define a Class That Can Provide Identical Functionality on Different Data Types (Visual Basic)

You can define a class from which you can create objects that provide identical functionality on different data types. To do this, you specify one or more type parameters in the definition. The class can then serve as a template for objects that use various data types. A class defined in this way is called a generic class.

The advantage of defining a generic class is that you define it just once, and your code can use it to create many objects that use a wide variety of data types. This results in better performance than defining the class with the Object type.

In addition to classes, you can also define and use generic structures, interfaces, procedures, and delegates.

To define a class with a type parameter

  1. Define the class in the normal way.

  2. Add (Of typeparameter) immediately after the class name to specify a type parameter.

  3. If you have more than one type parameter, make a comma-separated list inside the parentheses. Do not repeat the Of keyword.

  4. If your code performs operations on a type parameter other than simple assignment, follow that type parameter with an As clause to add one or more constraints. A constraint guarantees that the type supplied for that type parameter satisfies a requirement such as the following:

    • Supports an operation, such as >, that your code performs

    • Supports a member, such as a method, that your code accesses

    • Exposes a parameterless constructor

    If you do not specify any constraints, the only operations and members your code can use are those supported by the Object Data Type. For more information, see Type List.

  5. Identify every class member that is to be declared with a supplied type, and declare it As typeparameter. This applies to internal storage, procedure parameters, and return values.

  6. Be sure your code uses only operations and methods that are supported by any data type it can supply to itemType.

    The following example defines a class that manages a very simple list. It holds the list in the internal array items, and the using code can declare the data type of the list elements. A parameterized constructor allows the using code to set the upper bound of items, and the parameterless constructor sets this to 9 (for a total of 10 items).

    Public Class simpleList(Of itemType)
      Private items() As itemType
      Private top As Integer
      Private nextp As Integer
      Public Sub New()
        Me.New(9)
      End Sub
      Public Sub New(ByVal t As Integer)
        MyBase.New()
        items = New itemType(t) {}
        top = t
        nextp = 0
      End Sub
      Public Sub add(ByVal i As itemType)
        insert(i, nextp)
      End Sub
      Public Sub insert(ByVal i As itemType, ByVal p As Integer)
        If p > nextp OrElse p < 0 Then
          Throw New System.ArgumentOutOfRangeException("p", 
            " less than 0 or beyond next available list position")
        ElseIf nextp > top Then
          Throw New System.ArgumentException("No room to insert at ", 
            "p")
        ElseIf p < nextp Then
          For j As Integer = nextp To p + 1 Step -1
            items(j) = items(j - 1)
          Next j
        End If
        items(p) = i
        nextp += 1
      End Sub
      Public Sub remove(ByVal p As Integer)
        If p >= nextp OrElse p < 0 Then
            Throw New System.ArgumentOutOfRangeException("p", 
                " less than 0 or beyond last list item")
        ElseIf nextp = 0 Then
            Throw New System.ArgumentException("List empty; cannot remove ", 
                "p")
        ElseIf p < nextp - 1 Then
            For j As Integer = p To nextp - 2
                items(j) = items(j + 1)
            Next j
        End If
        nextp -= 1
      End Sub
      Public ReadOnly Property listLength() As Integer
        Get
          Return nextp
        End Get
      End Property
      Public ReadOnly Property listItem(ByVal p As Integer) As itemType
        Get
          If p >= nextp OrElse p < 0 Then
            Throw New System.ArgumentOutOfRangeException("p", 
              " less than 0 or beyond last list item")
            End If
          Return items(p)
        End Get
      End Property
    End Class
    

    You can declare a class from simpleList to hold a list of Integer values, another class to hold a list of String values, and another to hold Date values. Except for the data type of the list members, objects created from all these classes behave identically.

    The type argument that the using code supplies to itemType can be an intrinsic type such as Boolean or Double, a structure, an enumeration, or any type of class, including one that your application defines.

    You can test the class simpleList with the following code.

    Public Sub useSimpleList()
      Dim iList As New simpleList(Of Integer)(2)
      Dim sList As New simpleList(Of String)(3)
      Dim dList As New simpleList(Of Date)(2)
      iList.add(10)
      iList.add(20)
      iList.add(30)
      sList.add("First")
      sList.add("extra")
      sList.add("Second")
      sList.add("Third")
      sList.remove(1)
      dList.add(#1/1/2003#)
      dList.add(#3/3/2003#)
      dList.insert(#2/2/2003#, 1)
      Dim s = 
        "Simple list of 3 Integer items (reported length " &
         CStr(iList.listLength) & "):" &
         vbCrLf & CStr(iList.listItem(0)) &
         vbCrLf & CStr(iList.listItem(1)) &
         vbCrLf & CStr(iList.listItem(2)) &
         vbCrLf &
         "Simple list of 4 - 1 String items (reported length " &
         CStr(sList.listLength) & "):" &
         vbCrLf & CStr(sList.listItem(0)) &
         vbCrLf & CStr(sList.listItem(1)) &
         vbCrLf & CStr(sList.listItem(2)) &
         vbCrLf &
         "Simple list of 2 + 1 Date items (reported length " &
         CStr(dList.listLength) & "):" &
         vbCrLf & CStr(dList.listItem(0)) &
         vbCrLf & CStr(dList.listItem(1)) &
         vbCrLf & CStr(dList.listItem(2))
      MsgBox(s)
    End Sub
    

See also