在vb6中克隆总是很痛苦。 弄错代码是如此容易,并且它引起的问题无穷无尽-通常是堆栈溢出。
在.Net中,您无需再进行任何克隆-您只需序列化对象,然后将其复制到目标对象中即可。 该技术得到了广泛的使用和描述-但是将它与泛型一起使用很有趣,因为这意味着您可以在应用程序中的任何位置使用它。 这是显示示例的代码示例:
Public Function CloneObject(Of T)(ByVal obj As T) As T
Try
Dim stream As New MemoryStream(1024)
Dim formatter As New BinaryFormatter()
formatter.Serialize(stream, obj)
stream.Seek(0, SeekOrigin.Begin) ' go back to the start
CloneObject = DirectCast(formatter.Deserialize(stream), T) 'get new object
stream.Close() ' clear down the memory
Catch excGeneric As Exception
ReportException(excGeneric)
End Try
End Function
您必须将您的类声明更改为可序列化才能使用以下代码:
<Serializable()> Friend Class ChargeUnitType
克隆任何对象的调用类似于以下内容:
Dim objClonedType As ChargeUnitType = CloneObject(ChargeUnitType)
有时,由于我不明白的原因,代码在尝试反序列化时失败,但是对于这些情况,在Microsoft的建议下,我将以下代码包含在要序列化的对象中,问题已消失:
Friend Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
From: https://bytes.com/topic/visual-basic/insights/779607-clone-any-object-vb-6-0-a