SomeMethod
Console.WriteLine("A.SomeMethod received " + x.ToString())
End Sub
End Class
CHAPTER 6 n INTERFACES 105
Class B
Implements IGeneric(Of Double)
Public Sub SomeMethod(ByVal x As Double) _
Implements IGeneric(Of Double).SomeMethod
Console.WriteLine("B.SomeMethod received " + x.ToString())
End Sub
End Class
Public Class EntryPoint
Shared Sub Main()
Dim ca As IGeneric(Of Integer) = New A()
Dim cb As IGeneric(Of Double) = New B()
ca.SomeMethod(123.456)
cb.SomeMethod(123.456)
End Sub
End Class
The previous code displays the following results when run:
A.SomeMethod received 123
B.SomeMethod received 123.456
In this example, the interface IGeneric(Of T) uses a type parameter, T, in both the interface
and its method. Class A then implements IGeneric as Integer, and the SomeMethod parameter
type becomes Integer. In Class B, these are implemented as Double. Option Strict Off permits
123.456 to be implicitly converted on the call to A.SomeMethod to allow a Double to be passed to
the Integer method.
Using a Generic Method in an Interface
Interfaces don??™t have to be generic to have generic members. Take a look at this example:
Option Strict On
Interface INonGeneric
Sub SomeMethod(Of T)(ByVal x As T)
End Interface
Class A
Implements INonGeneric
Public Sub SomeMethod(Of T)(ByVal x As T) _
Implements INonGeneric.
Pages:
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197