如何克隆Dictionary对象?

时间:2010-06-11 11:03:43

标签: dictionary vbscript clone

我在VBScript中有一个Dictionary对象。如何将其中包含的所有对象复制到新的Dictionary,即创建字典的克隆/副本?

3 个答案:

答案 0 :(得分:7)

创建一个新的Dictionary对象,遍历原始字典中的键,并将这些键和相应的值添加到新字典中,如下所示:

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

在大多数情况下,这应该足够了。但是,如果原始字典包含对象,则必须实现深度克隆,即克隆这些对象。

答案 1 :(得分:0)

如果有人正在寻找 VBA 解决方案,以下函数将执行字典的“深度克隆”,包括嵌套的字典对象。

' Compare mode for cloning dictionary object
' See CloneDictionary function
Public Enum eCompareMethod2
    ecmBinaryCompare = 0
    ecmTextCompare = 1
    ecmDatabaseCompare = 2
    ' Added this to use original compare method
    ecmSourceMethod = 3
End Enum


'---------------------------------------------------------------------------------------
' Procedure : CloneDictionary
' Author    : Adam Waller
' Date      : 3/30/2021
' Purpose   : Recursive function to deep-clone a dictionary object, including nested
'           : dictionaries.
'           : NOTE: All other object types are cloned as a reference to the same object
'           : referenced by the original dictionary, not a new object.
'---------------------------------------------------------------------------------------
'
Public Function CloneDictionary(dSource As Dictionary, _
    Optional Compare As eCompareMethod2 = ecmSourceMethod) As Dictionary

    Dim dNew As Dictionary
    Dim dChild As Dictionary
    Dim varKey As Variant

    ' No object returned if source is nothing
    If dSource Is Nothing Then Exit Function

    ' Create new dictionary object and set compare mode
    Set dNew = New Dictionary
    If Compare = ecmSourceMethod Then
        ' Use the same compare mode as the original dictionary.
        dNew.CompareMode = dSource.CompareMode
    Else
        dNew.CompareMode = Compare
    End If
    
    ' Loop through keys
    For Each varKey In dSource.Keys
        If TypeOf varKey Is Dictionary Then
            ' Call this function recursively to add nested dictionary
            Set dChild = varKey
            dNew.Add varKey, CloneDictionary(dChild, Compare)
        Else
            ' Add key to dictionary
            dNew.Add varKey, dSource(varKey)
        End If
    Next varKey
    
    ' Return new dictionary
    Set CloneDictionary = dNew
    
End Function

答案 2 :(得分:-2)

查看VBScript: How to utiliize a dictionary object returned from a function?中接受的答案。如果参考是所有正在寻找的东西,那么可能是一个解决方案。

编辑根据Ekkehard.Horner的评论,我现在明白这是不克隆,但可能会帮助那些只寻找原始对象引用的人。