【问题标题】:VB.Net - Inheritance - can parent and child both have ToString methods? Can both be accessed / used?VB.Net - 继承 - 父母和孩子都可以有 ToString 方法吗?两者都可以访问/使用吗?
【发布时间】:2012-05-28 15:50:10
【问题描述】:

我正在学习 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”

【问题讨论】:

    标签: vb.net inheritance tostring


    【解决方案1】:
    public Overloads Function ToString() as string 
        return MyBase.ToString() + "Some text"
    End Function
    

    【讨论】:

    • 谢谢GSerg!这正是我所需要的,而且非常有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多