如何使派生类可克隆?

时间:2014-10-30 14:27:01

标签: vb.net inheritance icloneable

我正在尝试创建一个实现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,如果这有任何区别的话。

1 个答案:

答案 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