剛了C# 2.0 的迭代器感覺不錯,簡潔明了。
在迭代器塊中用於向枚舉數對象提供值或發出迭代結束訊號。它的形式為下列之一:
yield return expression;
yield break;
在下面的樣本中,迭代器塊(這裡是方法 Power(int number, int power))中使用了 yield 語句。當調用 Power 方法時,它返回一個包含數字冪的可枚舉對象。注意 Power 方法的傳回型別是 IEnumerable(一種迭代器介面類型)。// yield-example.cs
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
}
}
}
輸出
2 4 8 16 32 64 128 256
這時,我就產生了一個問題, yield break; 是在迭代器中發出迭代結束訊號用的。可是,如果是在迭代器的使用的時候外層break了,迭代器怎麼能得到“訊號”呢??能否??因為,迭代器如果被中斷,迭代器內部要作一些處理,比如:關閉個串連什麼的, 如下代碼所示:// yield-break-example.cs
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
connection.Open();
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
connection.Close();
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
if(i > 8) break;
}
}
}
我的connection怎麼才能正常Close呢???