例如,我有一个名为Animal的基类。
Public MustInherit Class Animal
Public Property Name As String
Public Sub New(animalName As String)
Name = animalName
End Sub
Public Sub Sleep()
MsgBox("ZZZZZZZZZZZ")
End Sub
Public MustOverride Sub MakeSound()
End Class
子类可以实现以下一个或多个接口:
Public Interface IShed
Sub Shed()
End Interface
Public Interface IBeAJerk
Sub BeAJerk()
End Interface
我有3个子类:
Public Class Dog
Inherits Animal
Implements IShed
Public Sub New(dogName As String)
MyBase.New(dogName)
End Sub
Public Overrides Sub MakeSound()
MsgBox("Bark")
End Sub
Public Sub WagTail()
MsgBox("Wag")
End Sub
Public Sub DogShed() Implements IShed.Shed
MsgBox("Dog fur everywhere")
End Sub
End Class
Public Class Cat
Inherits Animal
Implements IShed
Implements IBeAJerk
Public Sub New(catName As String)
MyBase.New(catName)
End Sub
Public Overrides Sub MakeSound()
MsgBox("Meow")
End Sub
Public Sub Purr()
MsgBox("Purr")
End Sub
Public Sub CatShed() Implements IShed.Shed
MsgBox("Cat fur everywhere")
End Sub
Public Sub Ignore() Implements IBeAJerk.BeAJerk
MsgBox("Ignore owner")
End Sub
End Class
Public Class Snake
Inherits Animal
Implements IBeAJerk
Public Sub New(snakeName As String)
MyBase.New(snakeName)
End Sub
Public Overrides Sub MakeSound()
MsgBox("SSSSSS")
End Sub
Public Sub Slither()
MsgBox("Slither")
End Sub
Public Sub Bite() Implements IBeAJerk.BeAJerk
MsgBox("Bite owner")
End Sub
End Class
现在,我有一种方法,我想接受我知道实现IShed的动物(狗或猫)。 是否有一种方法可以在不确定动物类型的情况下进入界面?做类似的事情会很好:
Private Sub MakeAMess(sheddingAnimal As Animal.ThatImplementsIShed)
'I want to be able to access both IShed (Shed method) and
'Animal (Name property)
sheddingAnimal.Shed()
MsgBox(sheddingAnimal.Name & " made a mess!")
End Sub
我不想使IShed接口成为另一个抽象类,因为Cat和Snake都需要实现IBeAJerk接口。但是蛇没有脱落。 (实际上,我想蛇会剥皮,但是你明白我的意思。)
感谢您的帮助!
答案 0 :(得分:1)
我建议创建一个新接口IAnimal
,然后让IShed
扩展该接口(IBeAJerk
也是如此)。然后,类型Animal
将实现IAnimal
。然后,该方法将采用IShed
类型的参数。
Public Interface IAnimal
Property Name As String
Sub New(animalName As String)
Sub Sleep()
Sub MakeSound()
End Interface
Public Interface IShed
Inherits IAnimal
Sub Shed()
End Interface
Public Interface IBeAJerk
Inherits IAnimal
Sub BeAJerk()
End Interface
或者,您可以允许Animal
作为方法的参数,并在运行时检查传入的实例是否实现了IShed
,然后调用Shed
Private Sub MakeAMess(animal As Animal)
(TryCast(animal, IShed))?.Shed()
' additional code doing stuff with Animal
End Sub