将基类扩展到派生类 [英] Extending a base class to a derived class
问题描述
我们有两个类BasicRace& AdvancedRace. AdvancedRace继承自BasicRace
We have two classes BasicRace & AdvancedRace. AdvancedRace inherits from BasicRace
我有一个BasicRace,但我想将其转换"为高级类.
I have a BasicRace but i want to 'convert' it to the advanced class.
请参见下面的代码作为示例:
See code below as a example:
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
任何帮助都会很棒-我开始认为除非我编写一个将基本属性转换为AdvancedRace并逐个通过每个属性的函数,否则无法完成?
Any help would be great - I'm starting to think it can not be done unless i write a function to convert a basicRace to AdvancedRace going through each property one by one?
推荐答案
您不能像这样从基类转换"为子类(您不能更改现有对象的类型),但是可以创建子类的新实例,以从基类复制属性.
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:
-
AdvancedRace
中的构造函数,该构造函数采用BasicRace
参数并从中复制属性 -
AdvancedRace
中的静态方法,该方法采用一个BasicRace
参数,创建具有复制属性的新对象,然后将其返回
- a constructor in
AdvancedRace
that takes aBasicRace
parameter and copies properties from it - a static method in
AdvancedRace
that takes aBasicRace
parameter, creates the new object with copied properties, and then returns it
值得注意的是,这将导致两个完全独立的对象(每种类型中的一个)根本不链接-AdvancedRace
对象中的更改不会反映在BasicRace
中,反之亦然
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.
这篇关于将基类扩展到派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!