对派生类中的成员变量使用派生类型

时间:2019-10-01 17:30:52

标签: vb.net inheritance

是否有最佳方法来处理派生类中的成员变量(即在父类中声明的类型)?

例如,以下是简化的“制造商”和“汽车”类:

Public Class Manufacturer
    Protected _name As String
    Protected _country As String
End Class

Public Class Car
    Protected _manufacturer As Manufacturer

    Sub New(manufacturer)
        _manufacturer = manufacturer
    End Sub

End Class

如果我实现以下派生类:

Public Class Honda
    Inherits Manufacturer

    Sub New()
        _name = "Honda"
        _country = "Japan"
    End Sub

    Public Property Prefecture As String

End Class

Public Class Accord
    Inherits Car

    Sub New(manufacturer)

        MyBase.New(manufacturer)

        ' This doesn't work
        _manufacturer.Prefecture = "Tokyo"

    End Sub

End Class

我知道解决此问题的唯一方法是将_manufacturer强制转换为Honda

    Dim myManufacturer As Honda = manufacturer
    myManufacturer.Prefecture = "Tokyo"

我考虑过的另一种方法是为_manufacturer对象创建一个包装器:

Sub New(manufacturer As Honda)

    MyBase.New(manufacturer)

    MyManufacturer.Prefecture = "Tokyo"

End Sub

Private ReadOnly Property MyManufacturer() As Honda
    Get
        Return _manufacturer
    End Get
End Property

使用起来比较容易。

这些是我希望可以避免的额外步骤。谢谢您的指点。

1 个答案:

答案 0 :(得分:1)

一种方法是使Car成为通用类。

Public Class Car(Of T As Manufacturer)
    Protected _manufacturer As T

    Sub New(manufacturer As T)
        _manufacturer = manufacturer
    End Sub
End Class

然后,您可以将Accord声明为派生自Car的类,其中通用制造商类型为Honda

Public Class Accord
    Inherits Car(Of Honda)

    Sub New(manufacturer As Honda)
        MyBase.New(manufacturer)

        ' This should work
        _manufacturer.Prefecture = "Tokyo"
    End Sub
End Class