How do I clone a Dictionary object?

后端 未结 2 910
我寻月下人不归
我寻月下人不归 2021-01-17 20:33

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 di

2条回答
  •  青春惊慌失措
    2021-01-17 20:52

    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.

提交回复
热议问题