使用另一个类型为dict的变量初始化类型字典的一个变量

Raj*_*shS 2 vbscript vba qtp

Dim globalDict
Dim localDict
.
'Data from a excel is loaded to globalDict

Set localDict=globalDict(1)

localDict(item1)="AAA"
Run Code Online (Sandbox Code Playgroud)

此更新globalDict也会更新该值.它似乎localDict只是一个指针.

知道什么可能是错的吗?

谢谢,Rajesh

Jos*_*efZ 5

它是按设计:参见语句 下的Set Statement(VBScript):

通常,当您使用Set将对象引用分配给变量时,不会为该变量创建对象的副本.而是创建对对象的引用.多个对象变量可以引用同一个对象.因为这些变量是对象的引用(而不是副本),所以对象中的任何更改都会反映在引用它的所有变量中.

您可以按如下方式创建Dictionary对象的相同副本:

option explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName

Dim globalDict
Set globalDict = CreateObject("Scripting.Dictionary")
globalDict.Add "a", "Athens"    ' add some keys and items
globalDict.Add "b", "Belgrade"
globalDict.Add "c", "Cairo"

    ' create an identical copy of a Dictionary object
Dim localDict, arrKeys, arrItems, ii          ' declare variables
Set localDict = CreateObject("Scripting.Dictionary")
    arrKeys   = globalDict.Keys               ' get the keys
   'arrItems  = globalDict.Items              ' get the items: unnecessary
For ii= 0 To UBound( arrKeys)
   '(debug output) strResult = strResult & vbNewLine & arrKeys(ii) & vbTab & arrItems(ii)
   localDict.Add arrKeys(ii), globalDict( arrKeys(ii)) ' add appropriate keys and items
Next
    '           identical copy is created now

localDict("b") = "Brno"

strResult = strResult & vbNewLine & globalDict("b")
strResult = strResult & vbNewLine &  localDict("b")
strResult = strResult & vbNewLine & "-"
'strResult = strResult & vbNewLine & 

Wscript.Echo strResult ' the only `Echo` => run under `CScript.exe` or `WScript.exe`
Run Code Online (Sandbox Code Playgroud)

输出:

==> cscript D:\VB_scripts\SO\37644677.vbs
37644677.vbs
Belgrade
Brno
-
Run Code Online (Sandbox Code Playgroud)