2009-06-20 88 views
0

我有一些代碼想使用C#迭代器重構(即IEnumerable)。不幸的是,我看不出想要讓其他函數與迭代器一起工作而不導致重新啓動迭代器的最佳方式。如何重構迭代器的使用

例如:

NewLineEnumerator nle = new NewLineEnumerator(); 

while (bytesRead > 0) 
{ 
    var nlenum = nle.Process(inputData, bytesRead); 
    foreach (string block in nlenum) 
    { 
    DoSomething(nlenum); 
    } 
} 

void DoSomething(IEnumerable<string> myiter) 
{ 
    foreach (var s in myiter) 
    { 
    // myiter is restarted, and begins at the start of the iterator again 
    } 
} 

你可能會問,爲什麼我會想這樣做。原因是我擁有一個由「命令塊」包圍的數據流。根據命令,我將它發送到不同的子功能進行處理。所以我想繼續迭代我在開始或結束時停止在流中的位置。

此處有任何建議嗎?

回答

2

正如Nick所說,創建一個IEnumerator<string>並在方法之間傳遞它。該代碼看起來像這樣:

NewLineEnumerator nle = new NewLineEnumerator();

while (bytesRead > 0) 
{ 
    var nlenum = nle.Process(inputData, bytesRead); 
    using (var enumerator = nlenum.GetEnumerator()) 
    { 
     while (enumerator.MoveNext()) 
     { 
      DoSomething(enumerator); 
      Console.WriteLine(enumerator.Current); 
     } 
    } 

    // ensure that bytesRead is decremented by the code that runs above 
} 

void DoSomething(IEnumerator<string> myenum) 
{ 
    while (myenum.MoveNext()) 
    { 
     if (ShouldProcess(myenum.Current)) 
     { 
      // process it 
     } 
     else 
     { 
      // return to outer loop 
      break; 
     } 
    } 
} 

(請注意,如果你使用.NET 1.0和IEnumerable,不IEnumerable<string>,則using聲明可能不編譯。)

5

通過IEnumerator <字符串>而不是IEnumerable <字符串>,通過調用GetEnumerator()。它將保持呼叫狀態。

+0

但是,你不能在foreach – 2009-06-20 01:02:36