Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vb.net - how to make a deep copy of my list

 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 = TmDataSet.T.Rows(0)(i)
        Dim j = 0
        Do Until IsDBNull(TmDataSet.T.Rows(j + 1)(i))
            j += 1
            Do Until (TmDataSet.T.Rows(j)(i) <> -1)
                j += 1
            Loop
            If IsDBNull(TmDataSet.T.Rows(j + 1)(i)) Then Exit Do
            Dim new_st As New station
            new_st.t = TmDataSet.T.Rows(j)(i)
            new_st.name = TmDataSet.T.Rows(j)(1)
            new_st.id = TmDataSet.T.Rows(j)(2)
            new_st.id_t = new_st.id.ToString & new_st.t
            Dim new_st2 As New station
            Do Until (TmDataSet.T.Rows(j + 1)(i) <> -1)
                j += 1
            Loop
            new_st2.t = TmDataSet.T.Rows(j + 1)(i)
            new_st2.name = TmDataSet.T.Rows(j + 1)(1)
            new_st2.id = TmDataSet.T.Rows(j + 1)(2)
            new_st2.id_t = new_st2.id.ToString & new_st2.t

            Dim list As New List(Of station)
            list.Add(new_st)
            list.Add(new_st2)
            new_t.st.Add(list)
        Loop
        per_network.Add(new_t)
    Loop

' network = deep copy of per_network

vb >>> I just want to copy the content of per_network to network, I have tried ToList method but it was shallow copy and fail to perform clone method I didn't get it at all

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    <System.Runtime.CompilerServices.Extension()> _
    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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...