The enumerator that declares the IEnumerator
To create an enumerator for a non-generic interface, you must declare the class that implements the IEnumerator interface, and the IEnumerator interface has the following characteristics:
1, she is a member of the System.Collections namespace
2, it contains 3 methods current, MoveNext and reset
For example, the following code implements an enumerator class that lists the color array groups:
Using System.Collections;
Class Colorenumerator:ienumerator
{
string [] Colors;
int position=-1;
The public object,
{get
{
if (position==-1), return
new Exception ();
if (position==colors.length) return the
new Exception ();
return colors[position];
}
public bool MoveNext ()
{
if (position<colors.length-1)
{
position++;
return true;
}
else
{return
false;
}
}
pulic void Reset ()
{
position=-1
}
Public Colorenumerator (string[] thecolors)
{
colors=new string[thecolors.length];
for (int i=0;i<thecolors.length;i++)
{
colors[i]=thecolors[i];
}
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/csharp/
The IEnumerable interface has only one member--getenumerator method, which returns an enumerator for the object.
The following code gives an instance of using the Colorenumerator enumerator class above, and remember that Colorenumerator implements IEnumerator.
Class mycolors:ienumerable
{
string[] colors={"", "", ""};
Public IEnumerator GetEnumerator ()//Returns an object of type IEnumerator, which is the enumerable type
{return
new Colorenumerator (Colors);
}