向下转换与直通法

时间:2015-10-09 13:00:33

标签: vb.net inheritance interface

如果要实现接口并仍然使用共享方法继承基类,是否有一种访问基类方法的首选或最佳实践方法?而不是让Select Case检查派生类的类型,是否也可以使用下面的传递方法?

(这不是一个真正的项目,我尽可能通过创建尽可能少的示例来尽可能地简化问题 - 因此它可能不是使用此类功能的最佳方式。)

Public Class Form1
Dim obj As ICharacter

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    obj = New Fighter
    obj.Attack()
    obj.Say("I am a fighter!")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    obj = New Mage
    obj.Attack()
    obj.Say("I am a mage!")
End Sub
End Class

Interface ICharacter
Sub Attack()
Sub Say(ByVal Dialogue As String)
End Interface

Public Class BaseCharacter
Public Shared Sub Say(ByVal Dialogue As String)
    Debug.WriteLine(Dialogue)
End Sub
End Class

Public Class Fighter
Inherits BaseCharacter
Implements ICharacter

Public Sub Attack() Implements ICharacter.Attack
    Debug.WriteLine("This class swings a sword!")
End Sub

Public Overloads Sub Say(ByVal Dialogue As String) Implements ICharacter.Say
    BaseCharacter.Say(Dialogue)
End Sub
End Class

Public Class Mage
Inherits BaseCharacter
Implements ICharacter

Public Sub Attack() Implements ICharacter.Attack
    Debug.WriteLine("This class casts a spell!")
End Sub

Public Overloads Sub Say(ByVal Dialogue As String) Implements ICharacter.Say
    BaseCharacter.Say(Dialogue)
End Sub
End Class

我正在寻找类似的替代方案:

If TypeOf obj Is Mage Then
  CType(obj, Mage).Say("I am a mage!")
ElseIf TypeOf obj Is Fighter Then
  CType(obj, Fighter).Say("I am a fighter!")
End If

或:

Select Case obj.GetType()
  Case GetType(Mage)
    CType(obj, Mage).Say("I am a mage!")
  Case GetType(Fighter)
    CType(obj, Fighter).Say("I am a fighter!")
End Select

1 个答案:

答案 0 :(得分:2)

您的基类可以包含Type,每个类的New都会设置该值。这会阻止你在你的情况下做一个GetType。

Public Class BaseCharacter
  Enum TypeOfCharacter
     Mage
     Fighter
  End Enum

  Public Property Type As TypeOfCharacter

  Public Shared Sub Say(ByVal Dialogue As String)
      Debug.WriteLine(Dialogue)
  End Sub
End Class

然后您可以为字符串添加字典。

   Dim speech As New Dictionary(Of BaseCharacter.TypeOfCharacter, String)

   speech.Add(BaseCharacter.TypeOfCharacter.Mage, "I am a mage!")
   speech.Add(BaseCharacter.TypeOfCharacter.Fighter, "I am a fighter!")

   obj.Say(speech(obj.Type))

但是在你的例子中,字符串可以很容易地在实际的类中。

Public Class Fighter
  Inherits BaseCharacter
  Implements ICharacter

  Public Overloads Sub SayName()
     BaseCharacter.Say("I am a fighter!")
   End Sub
End Class

Public Class Mage
  Inherits BaseCharacter
  Implements ICharacter

  Public Overloads Sub SayName()
    BaseCharacter.Say("I am a mage!")
  End Sub
End Class