当子类调用超类时,如何让超类引用子类中的属性?方法?

时间:2015-03-26 19:23:10

标签: vb.net

超类:

Public MustInherit Class Product
  Friend _shortName as String = Nothing

  Public ReadOnly Property Name as String
    Get
      return _shortName
    End Get
  End Property

End Class

Sub class

Public Class MyProduct : Inherits Product
  Friend Shadows _shortName as String = "MyProd"
End Class

所以,在我调试的直接控制台中,我这样做:

Dim product as new MyProduct
product.Name ' => Nothing

product.Name应该是"MyProd" - 但它不是。如何正确设置它,以便超类中定义的属性访问子类中定义的字段?

1 个答案:

答案 0 :(得分:2)

基类无法访问该字段的阴影版本。除非绝对必要,否则应避免使用Shadows。对于这样的事情,您应该只从派生类更改基本字段的值。没有必要遮蔽它:

Public Class MyProduct : Inherits Product
    Public Sub New() 
        _shortName = "MyProd"
    End Sub
End Class

值得一提的是,除非您确实需要将其定义为Friend,否则基类中的_shortName字段的范围应为Protected

尽管在此示例中,您可能希望所有派生类提供名称。在这种情况下,有两种方法可以实现这一目标。您可以在基类的构造函数中将名称作为参数:

Public MustInherit Class Product
    Public Sub New(shortName As String)
        _shortName = shortName
    End Sub

    Friend _shortName As String = Nothing

    Public ReadOnly Property Name As String
        Get
            Return _shortName
        End Get
    End Property
End Class

Public Class MyProduct : Inherits Product
    Public Sub New()
        MyBase.New("MyProd")
    End Sub
End Class

在这种情况下,_shortName甚至不需要FriendProtected。理想情况下,其范围应为Private

或者,您可以简单地将该属性声明为MustOverride

Public MustInherit Class Product
    Public MustOverride ReadOnly Property Name As String
End Class

Public Class MyProduct : Inherits Product
    Public Overrides ReadOnly Property Name As String
        Get
            Return "MyProd"
        End Get
    End Property
End Class