1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
Namespace SampleHeritage
Class Animal
End Class
Class Cat : Inherits Animal
End Class
Class Dog : Inherits Animal
End Class
Class Mouse : Inherits Animal
End Class
Module M1
'We can create several overloads of the same method, specialized according to different combinations of their parameter types:
Sub ReactSpecialization([me] As Animal, other As Animal)
Console.WriteLine("{0} is not interested in {1}.", [me], other)
End Sub
Sub ReactSpecialization([me] As Cat, other As Dog)
Console.WriteLine("Cat runs away from dog.")
End Sub
Sub ReactSpecialization([me] As Cat, other As Mouse)
Console.WriteLine("Cat chases mouse.")
End Sub
Sub ReactSpecialization([me] As Dog, other As Cat)
Console.WriteLine("Dog chases cat.")
End Sub
'And now the magic part:
Sub React([me] As Animal, other As Animal)
ReactSpecialization([me], other)
End Sub
'This works because of the "as dynamic" cast, which tells the C# compiler,
'rather than just calling ReactSpecialization(Animal, Animal),
'to dynamically examine the type of each parameter and make a runtime choice
'about which method overload to invoke.
'To prove it really works:
Sub Test()
Dim cat As Animal = New Cat()
Dim dog As Animal = New Dog()
Dim mouse As Animal = New Mouse()
React(cat, dog)
React(cat, mouse)
React(dog, cat)
React(dog, mouse)
End Sub
'Output:
' Cat runs away from dog.
' Cat chases mouse.
' Dog chases cat.
' Dog is not interested in Mouse.
End Module
End Namespace |
Partager