我正在尝试创建一个实现ICloneable
的基类和派生类。在我看来,基类Clone
方法应该处理所有基类属性和派生类Clone
方法所有派生类属性并使用基类的Clone
方法。结果是这样的: -
Public Class MyBaseClass
Implements ICloneable
Private my_base_var As Integer
Public Function Clone() As Object Implements System.ICloneable.Clone
Dim new_base_class As MyBaseClass = New MyBaseClass
new_base_class.my_base_var = my_base_var
Return new_base_class
End Function
End Class
Public Class MySubClass
Inherits MyBaseClass
Implements ICloneable
Private my_sub_var As Integer
Public Overloads Function Clone() As Object Implements System.ICloneable.Clone
Dim new_sub_class As MySubClass = CType(MyBase.Clone, MySubClass) ' (1)
new_sub_class.my_sub_var = Me.my_sub_var
Return new_sub_class
End Function
End Class
这导致第(1)行的运行时异常Unable to cast object of type MyBaseClass to type MySubClass
,我承认这并不让我感到惊讶。用
Dim new_sub_class As MySubClass = MyBase.Clone
产生了编译错误。在我看来,我需要一些方法将MyBaseClass
转换为MySubClass
,以便使用基类Clone
设置基类的成员。一个不那么有吸引力的替代方法是复制子类的Clone
中的基类成员。有谁知道该怎么办?
我查看了问题here但无法将其转换为VB.Net。如果给出here的解决方案是必要的,那么我会放弃这个想法。在充实的时间里,我计划制作基类MustInherit
,如果这有任何区别的话。
答案 0 :(得分:2)
可能的实现可能如下所示:
Public Class MyBaseClass
Implements ICloneable
Private my_base_var As Integer = 1
Public Overridable Function Clone() As Object implements ICloneable.Clone
Dim theClone = Create()
theClone.my_base_var = my_base_var
Return theClone
End Function
Protected Overridable Function Create() As MyBaseClass
Return New MyBaseClass()
End Function
End Class
Public Class MySubClass
Inherits MyBaseClass
Private my_sub_var As Integer = 1
Public Overrides Function Clone() As Object
Dim theClone = DirectCast(MyBase.Clone(), MySubClass)
theClone.my_sub_var = Me.my_sub_var
Return theClone
End Function
Protected Overrides Function Create() As MyBaseClass
Return New MySubClass()
End Function
End Class