How to create a copy of a custom object or collection?

I have a custom collection β€” call her colParentA β€” and it contains several collections called colChild . I want to create a function that creates a new colParentB collection that has all the properties and contains the same children as colParentA . The user can then change several properties of colParentB that they need, instead of overriding those that are the same as colParentA .

colParentB should also contain new instances of colChild , which are copies found in `colParentA.

Can't I do it right?

 set colParentB = colParentA colParentB.Name = "Copy of " & colParentA.Name 

Because it just means that colParentB points to colParentA and is it changing colParentA properties colParentA ?

I'm confused. Thank you for your help.

+4
source share
1 answer

You are right in your suspicions - all that you assign are pointers, so it just refers to the same instance of an object with a different name.

You will probably need to create Clone functions on your colParent and colChild classes. That way, colChild.Clone can make a cloned member and return a new object with the same properties, and colParent can create a new collection with cloned colChild objects.

Be careful though, if any of the colParent or colChild properties is a reference to an object, then they can be cloned so that you do not update values ​​that you do not mean.

Possible functions (note that I assume that colChild contains several instances of the clsContent class - this will require a change):

colParent.Clone:

 Public Function Clone() as colParent 'Start a new parent collection dim parent as colParent set parent = new colParent 'Populate the new collection with clones of the originals contents dim child as colChild for each child in Me parent.Add(child.Clone) next set Clone = parent End Function 

colChild.clone:

 Public Function Clone() as colChild 'Start a new parent collection dim child as colChild set child = new colChild 'Populate the new collection with clones of the originals contents dim content as clsContent for each content in Me child.Add(content.Clone) next set Clone = child End Function 

clsContent.Clone:

  Public Function Clone() as clsContent 'Start a new parent collection dim content as clsContent set child = new clsContent child.Property1 = me.Property1 child.Property2 = me.Property2 ... set Clone = content End Function 

I apologize for any errors or typos - I do not have dev env, so I write directly to the text box!

+7
source

Source: https://habr.com/ru/post/1342722/


All Articles