2

我正在 VB.Net 中学习继承。一个家庭作业要求我编写一个带有名称(字符串)属性的基类和一个显示名称的 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 This is the name”

4

1 回答 1

2
public Overloads Function ToString() as string 
    return MyBase.ToString() + "Some text"
End Function
于 2012-05-28T15:52:08.753 回答