【发布时间】:2016-06-05 17:18:03
【问题描述】:
Dim globalDict
Dim localDict
.
'Data from a excel is loaded to globalDict
Set localDict=globalDict(1)
localDict(item1)="AAA"
此更新也更新了globalDict 中的值。好像localDict 只是一个指针。
知道可能出了什么问题吗?
谢谢, 拉杰什
【问题讨论】:
Dim globalDict
Dim localDict
.
'Data from a excel is loaded to globalDict
Set localDict=globalDict(1)
localDict(item1)="AAA"
此更新也更新了globalDict 中的值。好像localDict 只是一个指针。
知道可能出了什么问题吗?
谢谢, 拉杰什
【问题讨论】:
这是设计使然:参见Statements (VBScript)下的Set Statement:
通常,当您使用
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`
输出:
==> cscript D:\VB_scripts\SO\37644677.vbs
37644677.vbs
Belgrade
Brno
-
【讨论】: