如何克隆一个字典对象?

10

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

4个回答

12

创建一个新的 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

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


是的,那是真的...但是有没有内置功能来执行深度克隆? - Vineel Kumar Reddy
谢谢,这很有效,奇怪它不是VBA语言的一部分... - Damn
请注意,在向新字典添加数据之前,您需要设置.CompareMode - AdamsTips

1
如果有人正在寻找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

0

或者你可以只是:

将 dTEM 设为 dEQP

;)


这些变量名dTEMdEQP是什么意思。请附上额外的解释。 - sanitizedUser

-2

看一下VBScript:如何利用从函数返回的字典对象?中被接受的答案。如果只是在寻找引用,那么这可能是一个解决方案。

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


4
词典是对象,将对象传递给Subs / Functions / Methods(即使采用ByVal方式),将对象分配给值,并从Functions / Method返回对象(希望使用Set)将始终处理引用而不是克隆/复制/创建新的对象。因此,请删除您误导/错误的答案。 - Ekkehard.Horner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接