vb.net中运行时多态性的概念

时间:2013-07-15 12:15:58

标签: vb.net

考虑VB.NET中的以下示例

Module Module1
    Sub Main()
        Dim myCycle As Cycle

        'Here I am making a Superclass reference to hold a subclass object
        myCycle = New SportsCycle()
        Console.WriteLine("----Cycle Details--------")

        'Using this Object I am accessing the property Wheels of the Superclass Cycle
        Console.WriteLine("Number Of Wheels: " & myCycle.Wheels)

        'Using this Object I am accessing the property getTyp of the Subclass Cycle
        Console.WriteLine("Type Of Cycle: " & myCycle.getTyp) 'Line #1(This Line is showing error)

        Console.WriteLine("--------------------------")
        Console.ReadKey()
    End Sub
End Module
 
Public Class Cycle
    Private num_of_wheels As Integer

    Property Wheels As Integer
        Get
            Return num_of_wheels
        End Get
        Set(ByVal value As Integer)
            num_of_wheels = value
        End Set
    End Property
End Class
Public Class SportsCycle
    Inherits Cycle

    Private type As String

    Sub New()
        type = "RAZORBIKE"
        Wheels = 2
    End Sub

    ReadOnly Property getTyp As String
        Get
            Return type
        End Get
    End Property
End Class

上述程序显示错误,指出“'getTyp'不是其成员 问题。第1行中的循环“此处'问题'是我的项目名称。

请向我澄清这个概念。需要做什么?

1 个答案:

答案 0 :(得分:1)

尝试:

DirectCast(myCycle, SportsCycle).getTyp

原因是Cycle不包含SportsCycle所在的此属性。由于SportsCycle继承自Cycle,您可以转换为SportsCycle来访问该属性。