【问题标题】:How to create dictionary of dictionaries vbscript如何创建字典 vbscript 的字典
【发布时间】:2016-03-23 14:55:46
【问题描述】:

我正在尝试在 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")

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

【问题讨论】:

    标签: vbscript


    【解决方案1】:

    你只有

    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。我这样做了,它可以工作Set dictionary("DigitalInputOne") = CreateObject("Scripting.Dictionary") Set dictionary("DigitalInputTwo") = CreateObject("Scripting.Dictionary") For Each item In dictionary For Each element In dictElements dictionary(item).Add element, dictElements(element) Next Next,但我认为它不是很好。我不能使用类,因为我在 WinCC 中这样做。
    • 我会为此使用Class 并拥有Class 对象的Dictionary
    • @Lankymart 您是正确的,自定义类为 OP 的问题提供了一个很好的解决方案。如果您充实这个想法并将其添加为第二个答案,我会很乐意支持它。
    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多