基类的属性在子类中可能不公开

时间:2014-03-09 01:30:08

标签: vb.net inheritance

我有一个继承自父类的子类。此父类具有属性Id。在我的子类中,我想给出属性Id并将父Id标识更改为我的子类中的其他名称。

Public Class Product ' This is the base class
    Private _iId As Integer
    Public ReadOnly Property Id As Integer ' This is the Id from the product
        Get
            Return _iId
        End Get
    End Property
End Class

Public Class OrderProduct ' This is the child class
    Inherits Product

    Private _iId As Integer
    Public ReadOnly Property Id As Integer ' This has to be the Id of the Order
        Get
            Return _iId
        End Get
    End Property

    Private _iIdProduct As Integer
    Public ReadOnly Property IdProduct As Integer ' This has to be the Id of the Product
        Get
            Return ? ? ?
        End Get
    End Property
End Class

1 个答案:

答案 0 :(得分:1)

Public Class Product
  Protected iID As Int32 = -1
  Public Readonly Property ID As Int32
    Get
      Return iID
    End Get
  End Property
End Class


Public Class OrderProduct
  Inherits Product

  Protected  iID As Int32 = -1
  Public Shadows Readonly Property ID As Int32
    Get
      Return iID
    End Get
  End Property

  Public Readonly Property ProductID As Int32
    Get
      Return MyBase.ID
    End Get
  End Property
End Class

这是一个非常糟糕的主意。这将是对继承的明确滥用。而是考虑封装,其中OrderProduct具有Product和Order的属性。或者让您的Order类包含ProductIDOrderID

在派生类中重新定义ID是一个非常糟糕的主意。