Information Technology Reference
In-Depth Information
The IEnumerable Interface
The
IEnumerable
interface has only a single member, method
GetEnumerator
, which returns an
enumerator for the object.
Figure 20-4 shows class
MyClass
, which has three items to enumerate, and implements the
IEnumerable
interface by implementing the
GetEnumerator
method.
Figure 20-4.
The GetEnumerator method returns an enumerator object for the class.
The following code shows the form for the declaration of an enumerable class.
using System.Collections;
Implements the IEnumerable interface
↓
class MyClass : IEnumerable
{
public IEnumerator GetEnumerator { ... }
...
↑
}
Returns an object of type IEnumerator
The following code gives an example of an enumerable class that uses enumerator class
ColorEnumerator
from the previous example. Remember that
ColorEnumerator
derives from
IEnumerator
.
using System.Collections;
class MyColors: IEnumerable
{
string[] Colors = { "Red", "Yellow", "Blue" };
public IEnumerator GetEnumerator()
{
return
new ColorEnumerator(Colors)
;
}
↑
}