vb.net – 如何使派生类可克隆?

我试图创建一个基类和派生类,两者都实现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

这导致运行时异常无法将类型为MyBaseClass的对象转换为在第(1)行键入MySubClass,我承认这并不让我感到惊讶.用.替换该行

    Dim new_sub_class As MySubClass = MyBase.Clone

产生了编译错误.在我看来,我需要一些方法将MyBaseClass转换为MySubClass,以便使用基类的Clone设置基类的成员.一个不太吸引人的选择是在子类的Clone中复制基类的成员.有谁知道该怎么办?

我已经查看了问题here,但无法将其转换为VB.Net.如果给出here的解决方案是必要的,那么我会放弃这个想法.在充足的时间里,我计划创建基类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
点赞