![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
IEnumerable的GetEnumerator返回一个实现了IEnumerator接口的对象
实现IEnumerable接口的类,可以支持foreach循环遍历对象的集合元素
using System;
using System.Collections;
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
public IEnumerator GetEnumerator()
{
return new PeopleEnum(_people);
}
}
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
public object Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
class App
{
static void Main()
{
Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
//
C#中使用IEnumerator接口遍历集合!
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
ArrayList arlist = new ArrayList();
for (int i = 0; i <= 8; i++)
{
arlist.Add(i);
}
IEnumerator enumer = arlist.GetEnumerator(2,5);//这句返回从第二个元素起,找5个元素.结果为 2,3,4,5,6.如果此处换为GetEnumerator(),则返回所有
while (enumer.MoveNext()) //一定要先movenext,不然会有异常
{
Console.WriteLine(enumer.Current.ToString());
}
Console.ReadLine();
} }