Why does Hashtable iteration with `For Each` not work in VBScript?

Why is it possible to iterate ArrayListwith For Each, but not Hashtable?

Dim i

For Each i In CreateObject("System.Collections.ArrayList") ' no error
Next

For Each i In CreateObject("System.Collections.Hashtable") ' error
Next

Iteration Hashtablegives

The object does not support this property or method.

+4
source share
1 answer

Scripting languages ​​have a technical limitation; they can only use the default interface for the class. They have no concept of interfaces at all and no back-door to get another interface through IUnknown :: QueryInterface (). As you can in C # by clicking on the desired interface type. The iterator for an ArrayList looks like this:

private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable {
   // etc...
}

IEnumerator - , VBScript. Hashtable :

private class HashtableEnumerator : IDictionaryEnumerator, IEnumerable, ICloneable {
   // etc..
}

IDictionaryEnumerator , IEnumerable. VBScript Current MoveNext. , , . :

public class KeysCollection : ICollection, IEnumerable {
   // etc..
}

, CopyTo, Count, IsSynchronized SyncRoot . Microsoft , [ComDefaultInterface] . .


. , QI IEnumerable. #:

using System;
using System.Collections;
using System.Runtime.InteropServices;

namespace VBScript
{
    [ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IMapper {
        IEnumerable ToEnum(object itf);
    }

    [ComVisible(true), ProgId("VBScript.Mapper")]
    public class Mapper : IMapper {
        public IEnumerable ToEnum(object itf) {
            return (IEnumerable)itf;
        }
    }
}

32-, 64- Regasm. script:

Set table = CreateObject("System.Collections.Hashtable")
table.Add 1, "one"
table.Add 2, "two"
Set mapper = CreateObject("VBScript.Mapper")
For Each key in mapper.ToEnum(table.Keys)
   WScript.Echo key & ": " & table(key)
Next

:

Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.

1: one
2: two
+6

Source: https://habr.com/ru/post/1605916/


All Articles