How do I clone a Dictionary object?

帅比萌擦擦* 提交于 2019-12-01 14:59:08

问题


I have a Dictionary object in VBScript. How can I copy all the objects contained in it to a new Dictionary, i.e. create a clone/duplicate of the dictionary?


回答1:


Create a new Dictionary object, iterate through the keys in the original dictionary and adds these keys and the corresponding values to the new dictionary, like this:

Function CloneDictionary(Dict)
  Dim newDict
  Set newDict = CreateObject("Scripting.Dictionary")

  For Each key in Dict.Keys
    newDict.Add key, Dict(key)
  Next
  newDict.CompareMode = Dict.CompareMode

  Set CloneDictionary = newDict
End Function

This should be enough in most cases. However, if your original dictionary holds objects, you'll have to implement deep cloning, that is, clone these objects as well.




回答2:


Take a look at the accepted answer in VBScript: How to utiliize a dictionary object returned from a function?. Could be a solution if a reference is all that is being looked for.

Edit As per Ekkehard.Horner's comment, I understand now that this is not cloning, but may help others who are only looking for a reference to the original object.



来源:https://stackoverflow.com/questions/3022182/how-do-i-clone-a-dictionary-object

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