1

我们有两个类 BasicRace 和 AdvancedRace。AdvancedRace 继承自 BasicRace

我有一个 BasicRace,但我想将它“转换”为高级课程。

请参阅下面的代码作为示例:

Module Module1
    Sub Main()
        Dim bRace As New BasicRace With {.CourseID = 1, .MeetingDate = "2013-05-01", .RaceNumber = 1}
        Dim aRace As New AdvancedRace

        ' Upgrade bRace to AdvancedRace???????
    End Sub
End Module

Public Class BasicRace
    Public Property MeetingDate As Date
    Public Property CourseID As Integer
    Public Property RaceNumber As Integer
End Class

Public Class AdvancedRace
    Inherits BasicRace
    Public Property RaceTitle As String
End Class

任何帮助都会很棒 - 我开始认为它无法完成,除非我编写一个函数将 basicRace 转换为 AdvancedRace 逐个遍历每个属性?

4

1 回答 1

2

You can't "convert" from a base class to a subclass as such (you can't change the type of an existing object), but you can create new instance of the subclass that copies the properties from your base class.

Typical ways of implementing this for your classes might be:

  • a constructor in AdvancedRace that takes a BasicRace parameter and copies properties from it
  • a static method in AdvancedRace that takes a BasicRace parameter, creates the new object with copied properties, and then returns it

It's worth noting that this will result in two completely separate objects (one of each type) that aren't linked at all - changes in your AdvancedRace object won't be reflected in the BasicRace or vice-versa.

于 2013-05-03T08:26:38.653 回答