C#中IEnumerable接口用法實(shí)例分析
本文實(shí)例講述了C#中IEnumerable接口用法。分享給大家供大家參考。具體分析如下:
枚舉數(shù)可用于讀取集合中的數(shù)據(jù),但不能用于修改基礎(chǔ)集合。
最初,枚舉數(shù)定位在集合中第一個(gè)元素前。Reset 方法還會(huì)將枚舉數(shù)返回到此位置。在此位置上,Current 屬性未定義。因此,在讀取 Current 的值之前,必須調(diào)用 MoveNext 方法將枚舉數(shù)提前到集合的第一個(gè)元素。
在調(diào)用 MoveNext 或 Reset 之前,Current 返回同一對(duì)象。MoveNext 將 Current 設(shè)置為下一個(gè)元素。
如果 MoveNext 越過(guò)集合的末尾,枚舉數(shù)就會(huì)被放置在此集合中最后一個(gè)元素的后面,且 MoveNext 返回 false。當(dāng)枚舉數(shù)位于此位置時(shí),對(duì) MoveNext 的后續(xù)調(diào)用也返回 false。如果對(duì) MoveNext 的最后一次調(diào)用返回 false,則 Current 為未定義。若要再次將 Current 設(shè)置為集合的第一個(gè)元素,可以調(diào)用 Reset,然后再調(diào)用 MoveNext。
只要集合保持不變,枚舉數(shù)就保持有效。如果對(duì)集合進(jìn)行更改(如添加、修改或刪除元素),則枚舉數(shù)將失效且不可恢復(fù),而且其行為是不確定的。
枚舉數(shù)沒(méi)有對(duì)集合的獨(dú)占訪問(wèn)權(quán);因此,從頭到尾對(duì)一個(gè)集合進(jìn)行枚舉在本質(zhì)上不是一個(gè)線程安全的過(guò)程。若要確保枚舉過(guò)程中的線程安全,可以在整個(gè)枚舉過(guò)程中鎖定集合。若要允許多個(gè)線程訪問(wèn)集合以進(jìn)行讀寫(xiě)操作,則必須實(shí)現(xiàn)自己的同步。
下面的代碼示例演示如何實(shí)現(xiàn)自定義集合的 IEnumerable 接口。在此示例中,沒(méi)有顯式調(diào)用但實(shí)現(xiàn)了 GetEnumerator,以便支持使用 foreach(在 Visual Basic 中為 For Each)。此代碼示例摘自 IEnumerable 接口的一個(gè)更大的示例。
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
*
*/
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
c# 實(shí)現(xiàn)子窗口關(guān)閉父窗口也關(guān)閉的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)?lái)一篇c# 實(shí)現(xiàn)子窗口關(guān)閉父窗口也關(guān)閉的簡(jiǎn)單實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02

