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?
The foreach loop in C++ or more specifically, range-based for loop was introduced with the C++11. This type of for loop structure eases the traversal over an iterable data set. It does this by eliminating the initialization process and traversing over each and every element rather than an iterator.
The return type of this method is IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>. Which means by using iterator compiler will automatically create IEnumerable or IEnumerator interface for you there is no need to implement IEnumerable or IEnumerator interface in your class for using a foreach loop.
The IEnumerator interface provides iteration over a collection-type object in a class. The IEnumerable interface permits enumeration by using a foreach loop.
IEnumerable Returns the IEnumerator interface for a given object. IEnumerator Enables foreach style iteration of subtypes.
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 anIUnknown
interface to an object which implements the IEnumVARIANT
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With