Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

vb.net - Create a "clone" of this object, not point to it

Let's say I got a list called

myFirstList

And then I want to create a copy of that list so I can do some tweaks of my own. So I do this:

mySecondList = myFirstList
mySecondList.doTweaks

But I noticed that the tweaks also affect the myFirstList object! I only want the tweaks to affect the second one...

And afterwards I will want to completely delete mySecondList, so I do mySecondList = Nothing and I'm good, right?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Adam Rackis, I don't like your "Of course it does", because it is not at all obvious.

If you have a string variable that you assign to another string variabe, you do not change them both when making changes to one of them. They do not point to the same physical piece of memory, so why is it obvious that classes do?

Also, the thing is not even consistent. In the following case, you will have all elements in the array pointing at the same object (they all end up with the variable Number set to 10:

SourceObject = New SomeClass
For i = 1 To 10
   SourceObject.Number = i
   ObjectArray.Add = SourceObject   
Next i

BUT, the following will give you 10 different instances:

For i = 1 To 10
   SourceObject = New SomeClass
   SourceObject.Number = i
   ObjectArray.Add = SourceObject   
Next i

Apparently the scope of the object makes a difference, so it is not at all obvious what happens.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...