Scripting.Dictionary Lookup-add-if-not-present只有一个键搜索? [英] Scripting.Dictionary Lookup-add-if-not-present with only one key search?

查看:174
本文介绍了Scripting.Dictionary Lookup-add-if-not-present只有一个键搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查找 Scripting.Dictionary 中的键,以确保我们将它们(及其项目)只添加到字典中一次:

I am looking up keys in a Scripting.Dictionary to make sure I add them (and their items) only once to the dictionary:

If MyDict.Exists (Key) Then ' first internal key-value lookup
  Set Entry=MyDict.Item (Key)  ' Second internal key->value lookup
else
  Set Entry=New ItemType
  MyDict.Add Key,Entry
End If
' Now I work on Entry...

存在查找字典中的键, code> Item()也是这样做的。所以我得到一个逻辑查找操作的两个键查找。没有更好的方法吗?

Exists looks up the key in the dictionary, and Item () does it, too. So i get two key lookups for one logical lookup operation. Isn't there a better way?

项目的dox项目属性说


如果在尝试返回现有项目时找不到键,则会创建一个新的
键,并将其相应的项目留空。
MSDN

这是真的,即查找不存在的键显然使这个字典的关键部分,可能与关联的item =空。
但是那有什么好处? c Item()中创建密钥后,如何设置空项目?属性调用?

This is true, i.e. looking up a non-existant key obviously makes this key part of the dictionary, probably with associated item = empty. But what is that good for? How could I use this to boil it down to one lookup operation? How can I set the empty item after creating the key during the Item () property call?

推荐答案

我关键的问题是VBScript强制我们使用 Set 与对象,而不是一个对象。过去曾经使用过的一个技巧是使用 Array 函数为该值创建一个临时占位符。然后我可以检查数组以查看该值是否为一个对象。应用于您的示例:

The key problem to me is the fact that VBScript forces us to use Set with objects, and Empty is not an object. One trick that I've used in the past to get around this is to use the Array function to create a temporary placeholder for the value. Then I can check the array to see if the value is an object or not. Applied to your example:

tempArr = Array(dict.Item(key))
If IsEmpty(tempArr(0)) Then
    ' new entry
    Set entry = New MyClass
    ' can't use Add because the key has already been implicitly created
    Set dict.Item(key) = entry
Else
    ' existing entry
    Set entry = tempArr(0)
End If

在这种情况下,您尚未删除双重查找,但将其从现有条目案移动到新条目案。

In this case, though, you haven't eliminated the double lookup, but moved it from the "existing entry" case to the "new entry" case.

这篇关于Scripting.Dictionary Lookup-add-if-not-present只有一个键搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆