Deep copy of the object

May I get some help to make a deep copy of the 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 wrote myself.

What do I need to change for the Clone () function to return a deep copy?

+5
source share
2 answers

(Aside, I would probably call your class something other than a "class").

If you want to do all this manually, you will need to follow these steps:

  • , Field Clone(). , , , Clone(), Field, . Field , / (, ), Clone(), Clone() .
  • Clone() [], .
  • Name Name
  • List(Of Field), listA
  • A. :

For Each item in _ListOfFields
    listA.Add(item.Clone())
End

  1. (listA) , Clone()

(, ) , VB.NET, .

, , , ,

, , - " ".

+5

, :

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

, , .

: , , <Serializable()> 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

. , ICloneable , , . , .

+4

All Articles