The IEnumerable interface and the IEnumerator interface are very important interfaces in. NET. What are the differences between them?
1. in short, IEnumerable is a declarative interface. The class that declares the implementation of this interface is "iteratable enumerable", but it does not explain how to implement iterator ). the code is implemented as follows:
Public interface IEnumerable
{
IEnumerator GetEnumerator ();
}
2. The IEnumerator interface is an implementation interface. It declares that the class implementing this interface can be used as an iterator. Its code is implemented as follows:
Public interface IEnumerator
{
Object Current {get ;}
Bool MoveNext ();
Void Reset ();
}
3. To support Foreach traversal, a collection must implement IEnumerable and return the iterator object in a certain way: IEnumerator.
How can we implement these two interfaces? The Code is as follows:
Assume that there is a Person class, which has two attributes: FirstName and LastName.
Public class Person
{
Public string FirstName {get; set ;}
Public string LastName {get; set ;}
Public Person (string firstName, string lastName)
{
This. FirstName = firstName;
This. LastName = lastName;
}
}
In addition, the People class is used to implement the IEnumerable and IEnumerator interfaces.
// Implement the IEnumerable Interface
Public class People: IEnumerable
{
Public Person [] pers;
Public People (Person [] ps)
{
This. pers = ps;
}
Public IEnumerator GetEnumerator ()
{
// Foreach (Person p in pers)
//{
// Yield return p;
//}
Return new People1 (pers );
}
}
// Implement the IEnumerator Interface
Public class People1: IEnumerator
{
Public Person [] pers;
Public People1 (Person [] per)
{
This. pers = per;
}
Int position =-1;
Public bool MoveNext ()
{
Position ++;
Return position <pers. Length;
}
Public void Reset ()
{
Position =-1;
}
Public object Current
{
Get
{
Try
{
Return pers [position];
}
Catch (IndexOutOfRangeException ex)
{
Throw new InvalidOperationException ();
}
}
}
}