字典对象的Exists函数:向字典中添加不存在的键

3
Sub test()
    Dim authDict As Dictionary
    Set authDict = CreateObject("Scripting.Dictionary")

    authDict.Add "Anton", 1
    authDict.Add "Martin", "3"
    authDict.Add "Dave", 1

    testKey = authDict.Exists("Alina") ' False, but adding this Key to dictionary by itself
    testVal = authDict("Alina")
    testKey2 = authDict.Exists("Alina") ' now it true
    testVal2 = authDict("Alina")
End Sub

为什么在不存在状态字典的情况下,它们会自行添加此键到字典中?如何防止这种情况发生?

1
我认为通过使用行testVal = authDict("Alina"),它会添加到字典中。 - Mikku
为了避免这种行为,您需要使用像这个(https://gist.github.com/florentbr/12c90342af901b39350eaee6a72bed3d#file-4-dictionary-cls)一样的自定义字典。 - Florent B.
1个回答

4
这里的问题在于这一行。
testVal = authDict("Alina")

将项目Alina添加到字典中。因此,只有在它已经存在时才运行它,否则它将被创建。使用以下方式的Exists()方法:

If authDict.Exists("Alina") Then ' False, but adding this Key to dictionary by itself
    testVal = authDict("Alina")
Else
    MsgBox "Alina does not exist"
End If

为什么?

通过使用authDict("Alina"),您使用项目属性字典对象提交Alina作为参数key

因此,根据文档,项目属性"在字典对象中为指定的键设置或返回项目。"由于Alina尚不存在,因此没有任何内容可返回,因此默认情况下设置它。

项目属性的文档进一步说明:

如果更改项目时未找到键,则创建具有指定新项的新键。如果尝试返回现有项目时未找到键,则创建新键并将其对应的项目留为空。

来源:物品属性部分备注


我的问题是 - 为什么? - Dmitrij Holkin
5
根据设计,这是由微软编码的。您必须检查它是否存在,否则它将被自动创建。这是默认行为。为什么会这样,没有解释,因为这只是微软程序员选择的方式。 - Pᴇʜ
@DmitrijHolkin,请查看我编辑过的答案,现在包括了“为什么?”的答案。 - Pᴇʜ
如所提到的,它是根据设计来完成的。请参见字典文档,第5.3条将其分配给变量。 - L42

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接