What is the difference between the IEnumerable interface and the IEnumerator interface, which is a very important interface in. NET?
1. To put it simply, IEnumerable is a declarative interface, declaring that the class implementing the interface is an "iterative enumerable", but does not show how to implement an iterator (iterator). Its code is implemented as:
public interface IEnumerable
{
IEnumerator GetEnumerator ();
}
2. While the IEnumerator interface is an implementation interface, it declares that the class implementing the interface can be iterator as an iterator. Its code implementation is:
public interface IEnumerator
{
Object current {get;}
BOOL MoveNext ();
void Reset ();
}
3. A collection to support foreach traversal, you must implement IEnumerable and return the iterator object in one way: IEnumerator.
So how do you implement these two interfaces? The code is as follows:
Suppose there is a person class, which has two properties 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 IEnumerable and IEnumerator interfaces are implemented through the people class.
Implementing 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);
}
}
Implementing 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 ();
}
}
}
}
C # IEnumerable and IEnumerator differences, how to achieve