
136
|
Chapter 10: Generics
This is the Title of the Book, eMatter Edition
Copyright © 2006 O’Reilly & Associates, Inc. All rights reserved.
the System.Collections.Generic namespace. The Stack class is one of the collec-
tions enabled for generics.
Dim pileOfNumbers As New Stack(Of Integer)
Multiple Type Parameters
Some classes may require more than one generic type parameter. The Of keyword
supports multiple parameters, each separated by a comma.
Public Class SpecialCollection(Of T1, T2)
Public Sub TakeAction1(ByVal data1 As T1)
End Sub
Public Sub TakeAction2(ByVal data1 As T1, ByVal data2 As T2)
End Sub
Public Function GetResults( ) T2
End Sub
End Class
Constraints
In the class definition:
Public Class WorkGroup(Of T)
the T type parameter can be assigned to any type when an instance of the class is
created. Generics also allow you to place some restrictions or constraints on the
set of types used. For instance, if your custom generic class is only designed to
work with Windows Forms controls, allowing types like
Integer and String could
mess things up. Adding an
As clause to the type parameter limits the range of data
types that can be assigned to
T. For example, the class definition:
Public Class WorkGroup(Of T As System.Windows.Forms.Control)
limits T to the System.Windows.Forms.Control class or any class derived from it.
The following statements work:
Dim anyControls As WorkGroup(System.Windows.Forms.Control) ...