Instantiate Local Variable By Value?
I sort of understand why this is happening, but not entirely. I have a base class with a Shared
(Static
) variable, declared like so:
Public Shared myVar As New MyObject(arg1, arg2)
In a method of a derived class, I set a local variable like so:
Dim myLocalVar As MyObject = myVar
Now when I do something like myLocalVar.Property1 += value
, the value in Property1
persists to the next call of that method! I suppose I get why it would be happening; myVar
is being set by reference instead of by value, but I've never encountered anything like this before. Is there any way (other than my workaround which i开发者_运维问答s to just create a new object using the property values of myVar
) to create myLocalVar
by value?
When you create myLocalVar
you are creating a new reference to the same shared object. If you truly want a local copy of the shared instance you will need to create a true copy.
This is done by either cloning the instance or with a copy constructor on the type that allows you to create a copy of the instance. This is not as simple as it sounds, however, due to the differences between deep and shallow copying and a cloned or copied instance could create similar problems for you if the property you are accessing is simply a shallow-copied reference to the same instance that the property on the original instance is referencing.
The best thing I to do in this case is to create a local copy of only the parts of the shared instance that you need, rather than copying the entire object graph. This means create a local copy of whatever type Property1
is and using that.
精彩评论