how to make a deep copy of my list

后端 未结 2 1565
我寻月下人不归
我寻月下人不归 2020-12-21 11:46
 Dim i = 2
    Do While True
        i += 1
        If IsDBNull(TmDataSet.T.Rows(0)(i)) = True Then Exit Do
        Dim new_t As New train
        new_t.id = TmDataS         


        
2条回答
  •  离开以前
    2020-12-21 11:53

    You can create an extension method where you serialize the object only to deserialize it again. This will create a new object with it's own references, thus a Deep Copy.

    Public Module Extensions
         _
        Public Function DeepCopy(Of T)(ByVal Obj As T) As T
            If Obj.GetType().IsSerializable = False Then Return Nothing
    
            Using MStream As New MemoryStream
                Dim Formatter As New BinaryFormatter
                Formatter.Serialize(MStream, Obj)
                MStream.Position = 0
                Return DirectCast(Formatter.Deserialize(MStream), T)
            End Using
        End Function
    End Module
    

    Now you can just call:

    Dim network As List(Of train) = per_network.DeepCopy()
    

    EDIT:

    These are the required imports for my code above:

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

提交回复
热议问题