开发者

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

I have a custom collection - let's call it colParentA - and it contains a number of collections called colChild. I want to create a function that creates a new collection, colParentB that has all of the properties and contains the same children as colParentA. The user can then modify the few properties of colParentB that they need to, rather than having to redefine ones that are the same as colParentA.

colParentB should also contain new instances of colChild that are copies of those found in `colParentA.

I can't just do this right?

set colParentB = colParentA

colPar开发者_Python百科entB.Name = "Copy of " & colParentA.Name

Because this just makes colParentB point to colParentA and changes the properties of colParentA as well right?

I'm confused. Thanks for you help in advance.


You are correct in your suspicions - all you are assigning is pointers, so it'll just reference the same instance of the object with a different name.

You're probably going to need to create Clone functions on your colParent and colChild classes. That way colChild.Clone can do a memberwise clone and return a brand new object with the same properties, and colParent can create a new collection with the cloned colChild objects.

Be careful though, as if any of the properies of colParent or colChild are references to object then those may need to be cloned to to avoid you updating values you don't mean to.

Possible functions would be (note that I'm supposing the colChild contains a number of instances of a class clsContent - that'll need changing):

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

Please excuse any bugs or typos - I don't have a dev env handy, so I'm writing straight into the text box!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜