gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:40:50 26 4
gpt4 key购买 nike

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

产生了编译错误。在我看来,我需要某种方式来转换 MyBaseClassMySubClass为了让基类的成员设置基类的 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

关于vb.net - 如何使派生类可克隆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26655645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com