您可以通过调用此辅助函数来创建任何类的克隆:
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:传入的类及其作为属性公开的任何其他类必须被标记<Serializable()> https://msdn.microsoft.com/en-us/library/System.SerializableAttribute(v=vs.110).aspx为了使用BinaryFormatter.Serialize https://msdn.microsoft.com/en-us/library/System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(v=vs.110).aspx
如果您想让自己的类公开可克隆方法本身,您可以添加该方法并实现ICloneable https://msdn.microsoft.com/en-us/library/system.icloneable(v=vs.110).aspx界面如下:
<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:请注意 ICloneable 附带了它的份额争议 https://stackoverflow.com/q/699210/1366033因为它不会向调用者指示它是否正在执行深克隆或浅克隆。实际上,您不需要接口就能将方法添加到您的类中。