S
SyraJM
I’m running into a problem using Generics in my code. I’ve created a
contrived example below to illustrate my design goals and my confusion.
I declare an Interface called IAnimal. I create several classes that
implement this interface. Let’s call these classes Dog, Horse, Fish.
I create a List of Animals based on the Interface like this:
Dim animalListing As New List (Of IAnimal)
I then create instances of each of my classes and load these instances into
the list. Now I have a Dog, Horse and Fish in animalListing.
I’ve created a generic method as shown below.
Private Sub FeedAnimal(Of T As IAnimal)()
I want to iterate my list and call the method for each object instance –
basing the call on the type of the current object. I thought the code would
look like this:
For Each a As IAnimal In animalListing
FeedAnimal (Of a)
Next
However, this doesn’t work. Why? All I’ve had success with is adding some
sort of logic switch:
For Each a As IAnimal in animalListing
If TypeOf (a) Is Dog Then
FeedAnimal (Of Dog)()
ElseIf TypeOf (a) Is Horse Then
FeedAnimal (Of Horse)()
End If
Next
I’m obviously missing something obvious because my Generic code isn’t
“genericâ€.
contrived example below to illustrate my design goals and my confusion.
I declare an Interface called IAnimal. I create several classes that
implement this interface. Let’s call these classes Dog, Horse, Fish.
I create a List of Animals based on the Interface like this:
Dim animalListing As New List (Of IAnimal)
I then create instances of each of my classes and load these instances into
the list. Now I have a Dog, Horse and Fish in animalListing.
I’ve created a generic method as shown below.
Private Sub FeedAnimal(Of T As IAnimal)()
I want to iterate my list and call the method for each object instance –
basing the call on the type of the current object. I thought the code would
look like this:
For Each a As IAnimal In animalListing
FeedAnimal (Of a)
Next
However, this doesn’t work. Why? All I’ve had success with is adding some
sort of logic switch:
For Each a As IAnimal in animalListing
If TypeOf (a) Is Dog Then
FeedAnimal (Of Dog)()
ElseIf TypeOf (a) Is Horse Then
FeedAnimal (Of Horse)()
End If
Next
I’m obviously missing something obvious because my Generic code isn’t
“genericâ€.