G
Guest
I have a generic class defined. My "server" code wants to call methods on
the generic class after I've assigned the type to it. I was trying to do
this via a SELECT CASE statement but I can't seem to determine how to declare
the object at the module level (so I can use it in several methods) but
assign the type when I create the instance. Probably this isn't the
appropriate way to use Generics so if there are suggestions, I'm open to
them. Here is a contrived example of what I'm hoping to accomplish:
Public Interface IAnimal
Sub SitDown()
End Interface
Public Class AnimalServer(Of T As iAnimal)
Dim oAnimal As T
Public Sub GiveCommandToSit(ByVal oAnimal As T)
oAnimal.SitDown()
End Sub
End Class
Public Class Dog
Implements IAnimal
Public Sub SitDown() Implements IAnimal.SitDown
MsgBox("Dog sits")
End Sub
End Class
Public Class Cat
Implements IAnimal
Public Sub SitDown() Implements IAnimal.SitDown
MsgBox("Cat sits")
End Sub
End Class
Public Module Program
Dim oAnimalServer As AnimalServer(Of IAnimal) '?????
'commented out TryGeneric because project won't build
Private Sub TryGeneric()
'If 1 = 1 Then
' oAnimalServer = New AnimalServer(Of Dog) 'design-time error
'Else
' oAnimalServer = New AnimalServer(Of Cat) 'design-time error
'End If
'oAnimalServer.GiveCommandToSit()
End Sub
Sub Main()
'works fine
Dim oDogServer As New AnimalServer(Of Dog)
Dim oCatServer As New AnimalServer(Of Cat)
oDogServer.GiveCommandToSit(New Dog)
oCatServer.GiveCommandToSit(New Cat)
TryGeneric()
End Sub
End Module
the generic class after I've assigned the type to it. I was trying to do
this via a SELECT CASE statement but I can't seem to determine how to declare
the object at the module level (so I can use it in several methods) but
assign the type when I create the instance. Probably this isn't the
appropriate way to use Generics so if there are suggestions, I'm open to
them. Here is a contrived example of what I'm hoping to accomplish:
Public Interface IAnimal
Sub SitDown()
End Interface
Public Class AnimalServer(Of T As iAnimal)
Dim oAnimal As T
Public Sub GiveCommandToSit(ByVal oAnimal As T)
oAnimal.SitDown()
End Sub
End Class
Public Class Dog
Implements IAnimal
Public Sub SitDown() Implements IAnimal.SitDown
MsgBox("Dog sits")
End Sub
End Class
Public Class Cat
Implements IAnimal
Public Sub SitDown() Implements IAnimal.SitDown
MsgBox("Cat sits")
End Sub
End Class
Public Module Program
Dim oAnimalServer As AnimalServer(Of IAnimal) '?????
'commented out TryGeneric because project won't build
Private Sub TryGeneric()
'If 1 = 1 Then
' oAnimalServer = New AnimalServer(Of Dog) 'design-time error
'Else
' oAnimalServer = New AnimalServer(Of Cat) 'design-time error
'End If
'oAnimalServer.GiveCommandToSit()
End Sub
Sub Main()
'works fine
Dim oDogServer As New AnimalServer(Of Dog)
Dim oCatServer As New AnimalServer(Of Cat)
oDogServer.GiveCommandToSit(New Dog)
oCatServer.GiveCommandToSit(New Cat)
TryGeneric()
End Sub
End Module