Walking the CVector collection
The CVector class doesn’t need to work with For Each. It’s more efficient to iterate with an index anyway, as you can see from the Performance sidebar on page 218. But Visual Basic has an internal iterator class for arrays, so why shouldn’t CVector have an iterator class? If nothing else, it will show you how Visual Basic makes For Each work with arrays.
The CVectorWalker class has the standard code for implementing IVariantWalker and delegating CEnumVariant, so let’s ignore that and concentrate on its state variable. All it needs is an iCur variable initialized to 0.
‘ Private state data
Private iCur As Long
Private Sub Class_Initialize()
‘ Initialize position in collection
iCur = 0
§
You’ve already seen the code for the CVector class, but I had to go back and add one detail. You might remember that CVector is actually based on an array variable named av. I had to add a friend property that shared that array through an indexed property named Vector.
As usual with iterator classes, the More method is the most interesting part of the implementation:
Private Function IVariantWalker_More(v As Variant) As Boolean
‘ Move to next element
iCur = iCur + 1
‘ Return False if no more data
If iCur > connect.Last Then Exit Function
‘ Return element through reference
If IsObject(connect.Vector(iCur)) Then
Set v = connect.Vector(iCur)
Else
v = connect.Vector(iCur)
End If
IVariantWalker_More = True
End Function
More simply moves on to the next item until it passes the last item, as indicated by the Last property. Since CVector is a generic container, it has to check for objects and handle them differently.