Iterators)
Before learning the iterator, you must first understand the internal working method of foreach. To use foreach for an object, the object must have the getenumerator method, which is under the ienumerable interface. This method returns an instance of ienumerator. Therefore, an iterator must be used to implement the ienumerator interface. This interface mainly includes a current attribute and a movenext () method. This iterator class is used during foreach traversal. This is the iterator interface.
If a class needs to use foreach, it must implement the enumeration mode, but this mode is troublesome because it needs to maintain an internal state machine. Therefore, C #2.0 introduces the concept of iterator. C # When the compiler encounters an iterator, the content will be extended to the pencil in enumeration ModeCode.
Iterator syntax
It provides a shortcut for the combination of the iterator interface (ienumerable <t> and ienumerator <t>. The method of the iterator is the same as that implemented by the iterator interface.
We need to add support for the iterator interface.
Public class binarytree <t>: ienumerable <t>
{
Public ieumerator <t> getenumerator ()
{
Yield return first;
Yield return second;
}
// Because ienumerator <t> derives from ienumerator, so this function also required.
System. collection. ienumerator system. Collections. ienumerator. getenumerator ()
{
Return getenumerator ();
}
}
Iterator and status
When an iterator is called for the first time in a foreach statement, its status is initialized in the enumerator. Getenumerator () is called to obtain an iterator instance (referenced by iterator ). Then, every loop of foreach will call the movenext () method on the iterator instance. In the iterator, we use yield return to generate a value and return it to the foreach statement. After the return value is returned, the getenumerator () method stops. Wait until the next movenext) Request continues to execute the next yield return. This process ends until there are no more yield return statements in the iterator.
You can use yield break to cancel iteration.