C#中IEnumerable接口用法实例分析
本文实例讲述了C#中IEnumerable接口用法。分享给大家供大家参考。具体分析如下:
枚举数可用于读取集合中的数据,但不能用于修改基础集合。
最初,枚举数定位在集合中第一个元素前。Reset方法还会将枚举数返回到此位置。在此位置上,Current属性未定义。因此,在读取Current的值之前,必须调用MoveNext方法将枚举数提前到集合的第一个元素。
在调用MoveNext或Reset之前,Current返回同一对象。MoveNext将Current设置为下一个元素。
如果MoveNext越过集合的末尾,枚举数就会被放置在此集合中最后一个元素的后面,且MoveNext返回false。当枚举数位于此位置时,对MoveNext的后续调用也返回false。如果对MoveNext的最后一次调用返回false,则Current为未定义。若要再次将Current设置为集合的第一个元素,可以调用Reset,然后再调用MoveNext。
只要集合保持不变,枚举数就保持有效。如果对集合进行更改(如添加、修改或删除元素),则枚举数将失效且不可恢复,而且其行为是不确定的。
枚举数没有对集合的独占访问权;因此,从头到尾对一个集合进行枚举在本质上不是一个线程安全的过程。若要确保枚举过程中的线程安全,可以在整个枚举过程中锁定集合。若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。
下面的代码示例演示如何实现自定义集合的IEnumerable接口。在此示例中,没有显式调用但实现了GetEnumerator,以便支持使用foreach(在VisualBasic中为ForEach)。此代码示例摘自IEnumerable接口的一个更大的示例。
usingSystem;
usingSystem.Collections;
publicclassPerson
{
publicPerson(stringfName,stringlName)
{
this.firstName=fName;
this.lastName=lName;
}
publicstringfirstName;
publicstringlastName;
}
publicclassPeople:IEnumerable
{
privatePerson[]_people;
publicPeople(Person[]pArray)
{
_people=newPerson[pArray.Length];
for(inti=0;i<pArray.Length;i++)
{
_people[i]=pArray[i];
}
}
IEnumeratorIEnumerable.GetEnumerator()
{
return(IEnumerator)GetEnumerator();
}
publicPeopleEnumGetEnumerator()
{
returnnewPeopleEnum(_people);
}
}
publicclassPeopleEnum:IEnumerator
{
publicPerson[]_people;
//Enumeratorsarepositionedbeforethefirstelement
//untilthefirstMoveNext()call.
intposition=-1;
publicPeopleEnum(Person[]list)
{
_people=list;
}
publicboolMoveNext()
{
position++;
return(position<_people.Length);
}
publicvoidReset()
{
position=-1;
}
objectIEnumerator.Current
{
get
{
returnCurrent;
}
}
publicPersonCurrent
{
get
{
try
{
return_people[position];
}
catch(IndexOutOfRangeException)
{
thrownewInvalidOperationException();
}
}
}
}
classApp
{
staticvoidMain()
{
Person[]peopleArray=newPerson[3]
{
newPerson("John","Smith"),
newPerson("Jim","Johnson"),
newPerson("Sue","Rabon"),
};
PeoplepeopleList=newPeople(peopleArray);
foreach(PersonpinpeopleList)
Console.WriteLine(p.firstName+""+p.lastName);
}
}
/*Thiscodeproducesoutputsimilartothefollowing:
*
*JohnSmith
*JimJohnson
*SueRabon
*
*/
希望本文所述对大家的C#程序设计有所帮助。