Is it possible to make a custom container class implemented purely in VBScript (no COM objects) work with the For Each statement? If so, what methods must I expose?
1 Answer
In short, no
Why? To create an enumerable collection class to get something like
Class CTest
....
End Class
Dim oTest, mElement
Set oTest = New CTest
....
For Each mElement In oTest
....
Next
the class MUST follow some rules. We will need the class to expose
A public readonly property called
Count
A public default method called
Item
A public readonly property called
_NewEnum
, that should return an
IUnknown
interface to an object which implements theIEnumVARIANT
interface and that must have the hidden attribute and a dispatch ID of -4
And from this list or requirements, VBScript does not include any way to indicate the dispatch ID or hidden attribute of a property.
So, this can not be done
The only way to enumerate over the elements stored in a container class is to have a property (or method) that returns
an object that supports all the indicated requirements, usually the same object used to hold the elements (fast, but it will expose too much information)
an array (in VBScript arrays can be enumerated) holding references to each of the elements in the container (slow if the array needs to be generated on call, but does not return any non required information)
Foe Each
can work on arrays.