Sie sind auf Seite 1von 3

Deep Copying an Object in

VB.NET
A curious omission in .NET is the ability to make a deep copy of an object which is
independent of the original object – i.e. you can change the copy without changing
the original. If you simply copy an object in .NET with assignment, all you are doing is
pointing a second variable at the same object in memory, and if you change an
element of one object, you will change the other too.
https://www.rectanglered.com/deep-copying-object-vb-net 1/3
7/1/2018
If you want to do this, use Deep
this Copying
example of the de nition of a user object type ‘todo1’
an Object in VB.NET - Rectangle Red, Milton Keynes

as a guideline:

Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

<Serializable()> _
Public Class todo1
Implements ICloneable

Public placementid As Integer = 0


Public candidateid As Integer = 0
Public candidatename As String = ""
Public clientid As Integer = 0
Public clientname As String = ""
Public placementstartdate As Date = Nothing
Public placementenddate As Date = Nothing
Public readyforbilling As Boolean = False
Public fullday As Integer = 0
Public halfday As Integer = 0
Public chargerate As Decimal = 0.0
Public payrate As Decimal = 0.0
Public dateworked As Date = Nothing
Public candidatephone As String = ""
Public clientphone As String = ""
Public status As String = ""
Public key As String = ""

Public Function Clone() As Object Implements System.ICloneable.Clone


Dim m As New MemoryStream()
Dim f As New BinaryFormatter()
f.Serialize(m, Me)
m.Seek(0, SeekOrigin.Begin)
Return f.Deserialize(m)
End Function

End Class

The parts in italics are the bits you need to add to make the object cloneable.

https://www.rectanglered.com/deep-copying-object-vb-net 2/3
7/1/2018
In your code, you can thenDeep
do Copying
this: an Object in VB.NET - Rectangle Red, Milton Keynes

Dim t1 as todo1 = New todo1


Dim t2 as todo1 = t1.Clone

The 2 objects, t1 and t2 are now independent of each other.

https://www.rectanglered.com/deep-copying-object-vb-net 3/3

Das könnte Ihnen auch gefallen