Assignment “=” operator in VB.NET 1.1

℡╲_俬逩灬. 提交于 2019-12-19 11:40:36

问题


I'm "cloning" objects in my code. For instance:

objClone = objOriginal

My question is:

  1. Does the assignment operator in VB.NET 1.1 do a member-by-member copy of the objOriginal to objClone or does objClone simply point as a reference to memory referenced by objOriginal?

回答1:


It's a reference copy, if the type is a reference type (ie: classes). If it's a value type (Structure), it will do a member by member copy.




回答2:


What happens with the code that you show depends on what type objOriginal is:

  • If it is a reference type, objClone will reference the same instance as objOriginal
  • If it is a value type, objClone will be a new instance, with the same content as objOriginal

Note though, if it is a value type having any members being reference types, those members will reference the same instances as the original object (this is known as a shallow copy).

Examples:

Public Class Test
    Public Number As Integer
End Class

Dim objOriginal As New Test()
objOriginal.Number = 42
Dim objClone As Test
objClone = objOriginal

In this case, objClone and objOriginal will both reference the same instance of Test.

Public Structure Test
    Public Number As Integer
End Class

Dim objOriginal As New Test()
objOriginal.Number = 42
Dim objClone As Test
objClone = objOriginal

In this case, objClone and objOriginal will be different instances of Test, each with their own Integer instance in the Number field.

Public Class SomeValue
    Public Number As Integer
End Class
Public Structure Test
    Public Value As SomeValue
End Class

Dim objOriginal As New Test()
objOriginal.Value = New SomeValue()
objOriginal.Value.Number = 42
Dim objClone As Test
objClone = objOriginal

In this case, objClone and objOriginal will be two different instances of k, but both will reference the same instance of SomeValue through their Value member.




回答3:


I'm not sure about VB, but the C# version of assignment only does a shallow copy. (Edit: For reference types).



来源:https://stackoverflow.com/questions/1757654/assignment-operator-in-vb-net-1-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!