C#中IEnumerable接口用法實例剖析。本站提示廣大學習愛好者:(C#中IEnumerable接口用法實例剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是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(在 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#法式設計有所贊助。