VB.Net - 继承 - 父和子都可以使用ToString方法吗?可以访问/使用吗?

时间:2012-05-28 15:50:11

标签: vb.net inheritance tostring

我正在学习VB.Net中的继承。家庭作业要求我编写一个带有名称(String)属性的基类和一个显示名称的ToString方法。它还要求我创建基类的一些子类,并在这些子类中实现ToString方法。我可以从子类和基类调用ToString方法吗?

下面是一些示例代码:

我的基类:

Public MustInherit Class MyBaseClass
    Public Property Name as String

    Public Overloads Function ToString() as String
        Return Name
    End Function
End Class

我的孩子班:

Public Class ChildClass
    Inherits MyBaseClass

    Public Sub New()
        Name = "This is the name"
    End Sub

    public Overloads Function ToString() as string
        ' Is it possible to call my base class ToString and append the text to
        ' this ToString method? I realize I can simply access my Name property
        ' however this does not fulfill the requirements i was given
        return "Some text"
    End Function
End Class

使用上述代码的一些代码:

dim someObject as new ChildClass("Hello VB.Net ")
lblLabel.text = someObject.ToString()

再次,我想知道是否有办法在子类中调用ToString()方法,然后基类生成类似的输出:“Hello VB.Net这是名称”

1 个答案:

答案 0 :(得分:2)

public Overloads Function ToString() as string 
    return MyBase.ToString() + "Some text"
End Function