如何:定义可对不同数据类型提供相同功能的类 (Visual Basic)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. 相对于使用 Object 类型定义类而言,这样做的性能将会更好。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. (Of typeparameter ) 紧靠类名称之后添加 typeparameter,以指定一个类型参数。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. 不要重复 Of 关键字。Do not repeat the Of keyword.

  4. 如果代码是对类型形参执行操作,而不是简单的赋值,请在该类型形参后添加一个 As 子句,以便添加一个或多个 约束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

    如果未指定任何约束,则代码只能使用 Object Data Type支持的那些运算和成员。If you do not specify any constraints, the only operations and members your code can use are those supported by the Object Data Type. 有关详细信息,请参阅 Type ListFor more information, see Type List.

  5. 标识要使用所提供类型声明的每个类成员,然后将其声明为 As typeparameterIdentify 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. 确保代码只使用它可提供给 itemType的任何数据类型所支持的运算和方法。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. 它将列表保存在内部数组 items中,并且使用代码可声明列表元素的数据类型。It holds the list in the internal array items, and the using code can declare the data type of the list elements. 参数化构造函数允许使用代码设置的上限 items ,而无参数构造函数将此项设置为9个 (,总计10个项) 。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
    

    你可以声明来自 simpleList 的一个类来保存 Integer 值的列表,声明另一个类来保存 String 值的列表,再声明一个类来保存 Date 值。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.

    所用代码提供给 itemType 的类型实参可以是内部类型(如 BooleanDouble)、结构、枚举或任何类型的类,包括应用程序定义的类。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.

    可以使用以下代码测试类 simpleListYou 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