开发者

vbscript dictionary adding in loop producing existing key error

I'm simply trying to construct a dictionary of productIDs

dim viewableProductIDs : set viewableProductIDs = CreateObject("Scripting.Dictionary")
    do while not rsEntry.EOF
        viewableProductIDs.Add rsEntry("Product开发者_StackOverflowID"), true
        rsEntry.MoveNext
    loop

rsEntry is a ADODB Recordset and I have made sure, through exhaustive debbug printing, that my query is indeed returning unique productIDs and that the recordset has no duplicates. Yet someohow, vbscript insists on thinking there are duplicates. It'll add the first one fine, but after that it errors out on all the rest. I tried surrounding it with a check for existing key and it someohow thought they all, but the first, existed. Then in the end I'm left with a dictionary with only one entry in it.

Does anyone have any idea as to why it's doing this?


Try adding .Value:

viewableProductIDs.Add rsEntry("ProductID").Value, true

Explanation:

VBScript has a concept called "default" properties. For instance, the line

someString = rsEntry("ProductID")

really is shorthand for

someString = rsEntry.Fields.Item("ProductID").Value

where Fields, Item, and Value are all the default properties of their respective objects. The main problem here is in the last step of the chain: the difference between rsEntry("ProductID") and rsEntry("ProductID").Value. In the above example, since I didn't use the Set keyword, an object reference would be illegal for the right-hand side of the assignment. Since rsEntry("ProductID") evaluates to a Field object reference, the interpreter takes the next step and expands the default property of the Field object, Value. If I had done

Set someObj = rsEntry("ProductID")

the interpreter would have set someObj to the Field object reference.

Now here's the fun part: the Dictionary object can use any type of value as its keys. It's more common to use simple values like strings or numbers, but it's perfectly legal to use arrays or object references. Since an object reference is legal for the first argument of the Dictionary.Add method, the interpreter doesn't bother to expand the default property and simply uses the Field object reference as the key. Since the Field object reference doesn't change from record to record, you end up trying to add the same key over and over. Adding .Value makes it explicitly clear to the interpreter that you want the value, not the object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜