IEnumerable介面和IEnumerator介面是.NET中非常重要的介面,二者有何區別?
1. 簡單來說IEnumerable是一個聲明式的介面,聲明實現該介面的類就是“可迭代的enumerable”,但並沒用說明如何?迭代器(iterator).其代碼實現為:
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
2. 而IEnumerator介面是實現式介面,它聲明實現該介面的類就可以作為一個迭代器iterator.其代碼實現為:
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
3.一個collection要支援Foreach進行遍曆,就必須實現IEnumerable,並一某種方式返回迭代器對象:IEnumerator.
那麼又如何?這兩個介面呢? 其代碼如下:
假設有一個Person類,其有兩個屬性FirstName和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;
}
}
另外通過People類來實現IEnumerable和IEnumerator介面.
//實現IEnumerable介面
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);
}
}
//實現IEnumerator介面
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();
}
}
}
}