如何创建词典vbscript

如何创建词典vbscript,vbscript,Vbscript,我正在尝试用VBS创建一个字典字典,我可以让它工作;然而,我的次级字典似乎是通过引用而不是通过值来访问的 我试过这个: Dim s, fso, f, ts, str, fRead, line, i, dictElements, dictionary, screenItem Set s = CreateObject("System.Text.StringBuilder") Set fso = CreateObject("Scripting.FileSystemObject") Set dictEl

我正在尝试用VBS创建一个字典字典,我可以让它工作;然而,我的次级字典似乎是通过引用而不是通过值来访问的

我试过这个:

Dim s, fso, f, ts, str, fRead, line, i, dictElements, dictionary, screenItem
Set s = CreateObject("System.Text.StringBuilder")
Set fso = CreateObject("Scripting.FileSystemObject")
Set dictElements = CreateObject("Scripting.Dictionary")
Set dictionary = CreateObject("Scripting.Dictionary")

'add elements to dictionary
dictElements.Add "Name", "MyName"
dictElements.Add "Setpoint", 100.0
dictElements.Add "Process Value", 80.6

'Create Data Structure
dictionary.Add "DigitalInputOne", dictElements
dictionary.Add "DigitalInputTwo", dictElements

'test dictionary
dictionary("DigitalInputTwo")("Name")= "Hello"
dictionary("DigitalInputTwo")("Setpoint")= 40.123
HmiRuntime.Screens("Home").ScreenItems("Text field_1").Text = dictionary ("DigitalInputOne")("Name")
HmiRuntime.Screens("Home").ScreenItems("Text field_2").Text = dictionary("DigitalInputOne")("Setpoint")
HmiRuntime.Screens("Home").ScreenItems("Text field_3").Text = dictionary("DigitalInputOne")("Process Value")

HmiRuntime.Screens("Home").ScreenItems("Text field_4").Text = dictionary("DigitalInputTwo")("Name")
HmiRuntime.Screens("Home").ScreenItems("Text field_5").Text = dictionary("DigitalInputTwo")("Setpoint")
HmiRuntime.Screens("Home").ScreenItems("Text field_6").Text = dictionary("DigitalInputTwo")("Process Value")
当我更改其中一个值时,它会更改所有值,这使我认为我的元素字典是通过引用创建的。有没有办法通过价值实现这一点?我希望每个子字典都不同。

您只有

Set dictElements = CreateObject("Scripting.Dictionary")
一旦这样,您就只创建了一个子词典——并且设置了两个键来指向这一个子词典。相反,请执行以下操作:

Set dictElements = CreateObject("Scripting.Dictionary") 'create first sub-dict
dictionary.Add "DigitalInputOne", dictElements
Set dictElements = CreateObject("Scripting.Dictionary") 'create second sub-dict
dictionary.Add "DigitalInputTwo", dictElements

VBScript具有基于引用计数的垃圾回收。将第一个字典添加到顶级字典时,顶级字典现在会维护对它的引用。因此,当您将
dictElements
设置为第二个字典时,顶级字典将保持原始字典的活动状态,因此不会对其进行垃圾收集。

这是否允许我创建模板,或者是否有更好的方法?我的大多数子字典都是相同的,只是有不同的值。我会写一个子字典,当它通过字典时,会以某种方式初始化它。然后按照3个步骤进行:1)创建字典,2)在字典上运行初始化子项,3)将其分配给顶级字典。我这样做了,它可以为dictElements字典(item)中的每个元素为字典中的每个项目工作
Set dictionary(“DigitalInputOne”)=CreateObject(“Scripting.dictionary”)Set dictionary(“Scripting.dictionary”)Set dictionary(“DigitalInputOne”)=下一步
,但我认为这不是很好。我不能使用类,因为我是在WinCC中这样做的。我会使用
,并拥有
对象的
字典。@Lankymart您是对的,自定义类可以很好地解决OP的问题。如果你把这个想法具体化,并把它作为第二个答案,我会很乐意投赞成票。