C#中IEnumerable接口用法實例分析
本文實例講述了C#中IEnumerable接口用法。分享給大家供大家參考。具體分析如下:
枚舉數可用于讀取集合中的數據,但不能用于修改基礎集合。
最初,枚舉數定位在集合中第一個元素前。Reset 方法還會將枚舉數返回到此位置。在此位置上,Current 屬性未定義。因此,在讀取 Current 的值之前,必須調用 MoveNext 方法將枚舉數提前到集合的第一個元素。
在調用 MoveNext 或 Reset 之前,Current 返回同一對象。MoveNext 將 Current 設置為下一個元素。
如果 MoveNext 越過集合的末尾,枚舉數就會被放置在此集合中最后一個元素的后面,且 MoveNext 返回 false。當枚舉數位于此位置時,對 MoveNext 的后續(xù)調用也返回 false。如果對 MoveNext 的最后一次調用返回 false,則 Current 為未定義。若要再次將 Current 設置為集合的第一個元素,可以調用 Reset,然后再調用 MoveNext。
只要集合保持不變,枚舉數就保持有效。如果對集合進行更改(如添加、修改或刪除元素),則枚舉數將失效且不可恢復,而且其行為是不確定的。
枚舉數沒有對集合的獨占訪問權;因此,從頭到尾對一個集合進行枚舉在本質上不是一個線程安全的過程。若要確保枚舉過程中的線程安全,可以在整個枚舉過程中鎖定集合。若要允許多個線程訪問集合以進行讀寫操作,則必須實現自己的同步。
下面的代碼示例演示如何實現自定義集合的 IEnumerable 接口。在此示例中,沒有顯式調用但實現了 GetEnumerator,以便支持使用 foreach(在 Visual Basic 中為 For Each)。此代碼示例摘自 IEnumerable 接口的一個更大的示例。
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];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
public PeopleEnum 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;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Person 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);
}
}
/* This code produces output similar to the following:
*
* John Smith
* Jim Johnson
* Sue Rabon
*
*/
希望本文所述對大家的C#程序設計有所幫助。

