Can I please have some help to perform a deep copy of an object.
Here is my code:
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 is a Class that I have written myself as well.
What do I need to modify for the Clone() Function to return a deep copy?
(As an aside, I probably would name your class something other than "Class").
If you wanted to do it all by hand you would need to follow steps like:
Clone()
method. If you haven't done this already, then this would likely involve itsClone()
method creating a new object of typeField
and then populating each of its properties based on the current object. If yourField
class has properties which are other classes/complex types (e.g. classes you have created yourself) then they should also implementClone()
and you should callClone()
on them to create new deep copiesClone()
method for the class you would create a new object of type [Class], e.g. by calling its constructorName
property of the new object to theName
property of your current objectList(Of Field)
, let's call it listA for the sake of exampleClone()
methodThere is an alternative (probably better) by-hand approach that is in VB.NET described here.
If you wanted to cheat a bit then you could just serialize your existing object and then deserialize it into a new object like the technique here
I would say the serialize then deserialize technique is the "easiest" one.
You can create a clone of any class by calling this helper function:
This works by serializing all the information from your class into a portable object and then rewriting it in order to sever any reference pointers.
If you want to make your own class expose the clonable method itself, you can add the method and implement the
ICloneable
interface like this: