首页 > 代码库 > IEnumerable

IEnumerable

 一个存储和获取 object 类型对象引用的集合,可以使用 foreach 进行遍历的集合。

namespace IEnumerableDemo
{
/// <summary>
/// 构建一个IEnumerable对象,遍历其中的元素
/// </summary>
class Program
{
static void Main(string[] args)
{
Person[] arrayperson = new Person[3]
{
new Person("xiaohon","zhang"),
new Person("xiaoguang","huang"),
new Person("xiaongming","lin")
};
People plist = new People(arrayperson);
foreach (Person p in plist)
Console.WriteLine(p.firstName + " " + p.lastName);
Console.ReadKey();
}
}

/// <summary>
/// 简单的业务对象
/// </summary>
public class Person
{
public string firstName;
public string lastName;

public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
}

/// <summary>
/// Person对象的集合:这个类实现一个IEnumerable,以便可以使用foreach进行遍历
/// </summary>
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];
}
}

//用于实现GetEnumerator方法
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}

public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}

}

/// <summary>
/// 当需要实现一个可以枚举遍历的对象,需要实现枚举子 IEnumerator.
/// </summary>
public class PeopleEnum : IEnumerator
{
public Person[] _people;

// 枚举子指针排位时,缺省指向第一个元素
// 当方法MoveNext()被调用时,才会指向下一个元素
int position = -1;

public PeopleEnum(Person[] list)
{
_people = list;
}

// 获取当前的项(只读属性)
public object Current
{
get
{
return _people[position];
}
}

// 将游标的内部位置向前移动
public bool MoveNext()
{
position++;
return (position < _people.Length);
}

// 将游标重置到第一个成员前面
public void Reset()
{
position = -1;
}
}
}

IEnumerable