http://www.cnblogs.com/zyylove2008/archive/2008/12/02/1345848.html
using System;
using System.Collections;//注意using Collections
using System.Collections.Generic;
using System.Text;
namespace EnumerableTest
{
class Program
{
static void Main(string[] args)
{
Person person = new Person();
foreach (string name in person)
{
Console.WriteLine(name);
}
Console.Read();
}
}
public class Person : IEnumerable
{
private string[] _items;
public string[] Items
{
get
{
return _items;
}
set
{
_items = value;
}
}
public Person()
{
_items = new string[] { "张成", "张尧成", "张军" };
}
#region IEnumerable Members
/// <summary>
/// 返回可循环访问集合的枚举数。
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return new PersonEnumerator(this);
}
#endregion
}
public class PersonEnumerator : IEnumerator
{
private int _index;
private Person _person;
public PersonEnumerator(Person person)
{
_index = -1;
_person = person;
}
#region IEnumerator Members
/// <summary>
/// 获取集合中的当前元素。
/// </summary>
public object Current
{
get
{
return _person.Items[_index];
}
}
/// <summary>
/// 将枚举数推进到集合的下一个元素。如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
return ++_index >= _person.Items.Length ? false : true;
}
/// <summary>
/// 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前
/// </summary>
public void Reset()
{
_index = -1;
}
#endregion
}
}