如何创建字典字典 vbscript

Fig*_*usa 5 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 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")
Run Code Online (Sandbox Code Playgroud)

当我更改其中一个值时,它会更改所有值,这让我认为我的元素字典是引用。有没有办法通过价值实现这一点?我希望每个子词典都不同。

Joh*_*man 5

你只有

Set dictElements = CreateObject("Scripting.Dictionary")
Run Code Online (Sandbox Code Playgroud)

一次,因此您只创建了一个子词典——并且设置了两个键来指向那个子词典。相反,请执行以下操作:

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
Run Code Online (Sandbox Code Playgroud)

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