4

我正在尝试创建一个都实现的基类和派生类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

这导致Unable to cast object of type MyBaseClass to type MySubClass第 (1) 行出现运行时异常,我承认这并不让我感到惊讶。将该行替换为

    Dim new_sub_class As MySubClass = MyBase.Clone

产生了编译错误。在我看来,我需要某种将 a 转换为的方法MyBaseClassMySubClass以便使用基类的Clone. 一个不太吸引人的替代方案是将基类的成员复制到子类的Clone. 有谁知道在这里做什么?

我已经查看了这里的问题,但无法将其转换为 VB.Net。如果这里给出的解决方案是必要的,那么我将放弃这个想法。MustInherit如果有什么不同的话,我计划在时间充裕的情况下制作基类。

4

1 回答 1

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
于 2014-10-30T14:53:33.397 回答