如何复制我的清单 [英] 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
'网络= per_network的深层副本
' network = deep copy of per_network
vb >>>我只想将per_network的内容复制到网络,我尝试了ToList方法,但是它是浅表复制,无法执行克隆方法,我根本没有得到它
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
推荐答案
您可以创建一个扩展方法,在该方法中,您可以序列化该对象,而只是再次对其进行反序列化.这将使用其自己的引用创建一个新对象,从而创建一个Deep Copy.
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
现在您可以致电:
Dim network As List(Of train) = per_network.DeepCopy()
这些是我上面的代码所必需的导入:
These are the required imports for my code above:
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
这篇关于如何复制我的清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文