我正在尝试创建一个基类和一个派生类,它们都实现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
中复制基类的成员。有人知道在这里该做什么吗?
我已经看过这里的问题,但无法将其转换为VB.Net。如果这里给出的解决方案是必要的,那么我将放弃这个想法。如果有什么不同的话,我计划在适当的时候制作基类MustInherit
。
可能的实现如下所示:
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