gpt4 book ai didi

vb.net - 对象的深拷贝

转载 作者:行者123 更新时间:2023-12-04 10:53:30 25 4
gpt4 key购买 nike

我可以请一些帮助来执行对象的深层复制。

这是我的代码:

Option Explicit On
Option Strict On

<Serializable> Public Class [Class]
Private _Name As String
Private _ListOfFields As New List(Of Field)

Public Property Name As String
Get
Return _Name
End Get
Set(value As String)
_Name = value
End Set
End Property

Public Property ListOfFields As List(Of Field)
Get
Return _ListOfFields
End Get
Set(value As List(Of Field))
_ListOfFields = value
End Set
End Property

Public Function Clone() As [Class]
Return DirectCast(Me.MemberwiseClone, [Class])
End Function

End Class

Field 也是我自己写的一个类。

我需要修改什么才能让 Clone() 函数返回深拷贝?

最佳答案

您可以通过调用此辅助函数来创建任何类的克隆:

Function DeepClone(Of T)(ByRef orig As T) As T

' Don't serialize a null object, simply return the default for that object
If (Object.ReferenceEquals(orig, Nothing)) Then Return Nothing

Dim formatter As New BinaryFormatter()
Dim stream As New MemoryStream()

formatter.Serialize(stream, orig)
stream.Seek(0, SeekOrigin.Begin)

Return CType(formatter.Deserialize(stream), T)

End Function

这是通过将类中的所有信息序列化为可移植对象然后重写它以切断任何引用指针来工作的。

Note: The passed in class and any other classes it exposes as properties must be marked <Serializable()> in order to use BinaryFormatter.Serialize



如果您想让自己的类公开可克隆方法本身,则可以添加该方法并实现 ICloneable 界面是这样的:

<Serializable()>
Public Class MyClass : Implements ICloneable

'NOTE - The Account class must also be Serializable
Public Property PersonAccount as Account
Public Property FirstName As String

Function Clone(ByRef orig As MyClass) As MyClass Implements ICloneable.Clone

' Don't serialize a null object, simply return the default for that object
If (Object.ReferenceEquals(orig, Nothing)) Then Return Nothing

Dim formatter As New BinaryFormatter()
Dim stream As New MemoryStream()

formatter.Serialize(stream, orig)
stream.Seek(0, SeekOrigin.Begin)

Return CType(formatter.Deserialize(stream), T)

End Function

End Class

Note: Be aware ICloneable comes with it's share of controversies as it does not indicate to the caller if it is performing a deep or shallow clone. In reality, you don't need the interface to be able to add the method to your class.

关于vb.net - 对象的深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15584053/

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