我正在学习VB.NET,我有一个关于复制Class实例的问题。
例如,我有
Public Class frmMain_CLT
Public Shared GEN_SETTING As MY_OBJ
Public Sub frmMain_CLT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Test_GM As MY_OBJ ' I would like to copy GEN_SETTING to Test_GM
End Sub
End Class
我想将GEN_SETTING复制到Test_GM
我知道我可以使用" Test_GM = GEN_SETTING"。但是,Test_GM将引用GEN_SETTING。因此,当我修改Test_GM中的数据时,GEN_SETTING中的数据将发生变化。
我想将GEN_SETTING的副本复制到Test_GM,这是" NOT"引用原始副本。
但我不知道该怎么办。我正在考虑DirectCast复制实例,但我收到错误..
更新
我刚刚在MY_OBJ类中创建了Clone方法
例如,
Public Function ShallowCopy() As MY_OBJ
Return DirectCast(Me.MemberwiseClone(), MY_OBJ)
End Function
但是,我不确定这是否是复制类实例的最佳方法
答案 0 :(得分:3)
这通常是在原始类中实现一个函数来完成的,该函数创建了引用的实例的克隆。
例如
Sub Main
Dim p = new Person() With {.FirstName = "Steve", .LastName = "King"}
Dim p1 = p.Clone()
p1.FirstName = "Steven"
Console.WriteLine(p.FirstName)
Console.WriteLine(p1.FirstName)
End Sub
Public Class Person
Public FirstName As String
Public LastName as String
Public Function Clone() as Person
return DirectCast(Me.MemberwiseClone(), Person)
End Function
End Class
在这里,您要求类p
的实例Person
使用基函数MemberWiseClone()创建自己的克隆。如果要克隆的类包含对其他类的内部引用,则事情会变得更加复杂。
例如,如果我们的Person类包含类Address
的实例,那么您还需要为类Address提供Clone方法并调用Address.Clone来创建Address类的不同实例在克隆的实例中。
Sub Main
Dim p = new Person() With {.FirstName = "Steve", .LastName = "King"}
p.AddressInfo = new Address() With {.City = "Rome"}
Dim p1 = p.Clone()
p1.FirstName = "Steven"
p1.AddressInfo.City = "Venice"
Console.WriteLine(p.FirstName)
Console.WriteLine(p.AddressInfo.City)
Console.WriteLine(p1.FirstName)
Console.WriteLine(p1.AddressInfo.City)
End Sub
Public Class Person
Public FirstName As String
Public LastName as String
Public AddressInfo as Address
Public Function Clone() as Person
Dim temp = DirectCast(Me.MemberwiseClone(), Person)
temp.AddressInfo = DirectCast(Me.AddressInfo.Clone(), Address)
return temp
End Function
End Class
Public Class Address
Public City as String
Public Function Clone() as Address
return DirectCast(Me.MemberwiseClone(), Address)
End Function
End Class
关于这些概念的一个有趣问题是What is the difference between a Deep Copy and a Shallow Copy