【VB.NET】多型

摘要:【VB.NET】多型

觀念

  • 和繼承一起使用
  • 同名異式
  • 有多個交替使用的類別,即使每個類別是以不同的方式來實作相同的屬性或方法

 

實作

 

做一個class,cls_0214_01.vb

Public Class cls_0214_01_cal

    Private m_x As Integer
    Private m_y As Integer

    Public Property X() As String
        Get
            Return m_x
        End Get
        Set(ByVal value As String)
            m_x = value
        End Set
    End Property

    Public Property Y() As String
        Get
            Return m_y
        End Get
        Set(ByVal value As String)
            m_y = value
        End Set
    End Property

    Public Overridable Function Answer() As Integer

    End Function

End Class

Public Class CalAdd
    Inherits cls_0214_01_cal

    Public Overrides Function Answer() As Integer
        Return X + Y
    End Function

End Class

Public Class CalSub
    Inherits cls_0214_01_cal

    Public Overrides Function Answer() As Integer
        Return X - Y
    End Function

End Class

 

做一個Form_0214_01.vb

Public Class Form_0214_01

    Dim myCal As cls_0214_01_cal
    Dim myCalAdd As New CalAdd()
    Dim myCalSub As New CalSub()

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        myCal = myCalAdd
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        myCal = myCalSub
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        txtX.Text = myCal.X
        txtY.Text = myCal.Y
        txtAnswer.Text = myCal.Answer

    End Sub

End Class


好文推薦

In 91 [物件導向]基礎篇:封裝、繼承、多型 (投影片分享)

 

 

既然走了! 就勇往的去 ......