[英]Do I have to use CopyTo to get a custom collection into an enumerable?
[英]When is custom enumerable/collection useful?
我訪問了不同的網站,試圖了解使用自定義枚舉的實時示例,我正在放棄這一行。 我有例子。 但他們讓我感到困惑。
例
拿1
class NumberArray
{
public int[] scores;
public NumberArray()
{
}
public NumberArray(int[] scores)
{
this.scores = scores;
}
public int[] Scores
{
get {return scores;}
}
}
拿2
public class Enumerator : IEnumerator
{
int[] scores;
int cur;
public Enumerator(int[] scores)
{
this.scores = scores;
cur = -1;
}
public Object Current
{
get {
return scores[cur];
}
}
public void Reset()
{
cur = -1;
}
public bool MoveNext()
{
cur++;
if (cur < scores.Length)
return true;
else return false;
}
}
public class Enumerable : IEnumerable
{
int[] numbers;
public void GetNumbersForEnumeration(int[] values)
{
numbers = values;
for (int i = 0; i < values.Length; i++)
numbers[i] = values[i];
}
public IEnumerator GetEnumerator()
{
return new Enumerator(numbers);
}
}
主要
static void Main()
{
int[] arr = new int[] { 1, 2, 3, 4, 5 };
NumberArray num = new NumberArray(arr);
foreach(int val in num.Scores)
{
Console.WriteLine(val);
}
Enumerable en = new Enumerable();
en.GetNumbersForEnumeration(arr);
foreach (int i in en)
{
Console.WriteLine(i);
}
Console.ReadKey(true);
}
在第2部分中,我按照自定義迭代迭代相同的整數數組,就像我在第1步中所做的那樣。為什么我應該通過使用自定義迭代來嘗試迭代整數 ?
可能我錯過了實時自定義迭代需求。 你能解釋一下我不能用現有的迭代工具做的任務嗎? ( 我剛完成學業,所以給我一個簡單的例子,這樣我就能理解它 )。
更新: 我從某個網站上獲取了這些示例。 該代碼沒有什么特別之處,即使不使用自定義迭代,我們也可以非常簡單地實現它,我的興趣是了解自定義迭代非常方便的真實場景。
當您迭代的資源沒有預先加載到內存中,而是在每次迭代中根據需要獲取時,自定義迭代器非常有用。 例如,在LINQ to SQL中,當您執行以下操作時:
foreach(var employee in dataContext.Employees) {
// Process employee
}
在foreach
循環的每個步驟中,查詢數據庫中的Employees表以獲取下一條記錄。 這樣,如果您提前退出循環,則不會讀取整個表,而只會讀取所需的記錄。
請參閱此處獲取實際示例: 枚舉文件中的行 。 這里,在foreach
循環的每次迭代中從文件中讀取每一行。 (作為旁注,.NET Framework 4提供了內置的相同功能)。
說實話,我並不完全確定你在問什么,但如果你擔心返回一個數組(如第1段)和返回迭代器(第2步)之間的區別,這是我的答案。
返回數組和返回迭代器之間有很大的不同。 返回數組意味着返回內部狀態(除非您將副本作為返回的一部分進行,但這很昂貴)。 如果返回迭代器,則只返回一個抽象,這將使調用者迭代狀態。 這也意味着,如果需要,你可以進行延遲評估(如果你返回一個數組,你顯然不能做的事情)。
此外,由於C#2中對迭代器的支持,實際上沒有理由手動實現IEnumerable。 有關其他詳細信息,請參閱此問題。 有人可以揭開yield關鍵字的神秘面紗嗎?
正如另一個自定義迭代在過去對我有用的例子是提供一個通用的抽象來遞歸地枚舉樹結構中的所有節點......
foreach (Node n in tree)
//...do something
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.