我正在看 Jon Skeet 的 Copenhagen C# talk视频,我最终得到了这段代码。
问题:
代码打印完成后发生了什么。我的意思是为什么 iterator.MoveNext()
失败了?
CODE:
class IteratorBlocks
{
public static IEnumerable<string> GetStringsForever()
{
string current = "";
char nextChar = 'a';
try
{
while (true)
{
current += nextChar;
nextChar++;
if (nextChar > 'z')
{
nextChar = 'a';
}
yield return current;
}
}
finally
{
Console.WriteLine("Finished");
}
}
}
class Program
{
static void Main(string[] args)
{
IEnumerable<string> strings = IteratorBlocks.GetStringsForever();
IEnumerator<string> iterator = strings.GetEnumerator();
for (int i = 0; i < 10; i++)
{
iterator.MoveNext();
Console.WriteLine(iterator.Current);
}
/*
I am not able to get what the code is doing beyond this line?
*/
iterator.Dispose();
for (int i = 0; i < 10; i++)
{
iterator.MoveNext();
Console.WriteLine(iterator.Current);
}
}
}
OUTPUT:
a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
Finished
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
最佳答案
调用 MoveNext()
只会返回 false
而不会执行任何其他操作,因为您已经处理了迭代器。 C# 编译器构建的状态机将进入“after”状态,并停留在那里。有关详细信息,请参阅 C# 3 规范的第 10.14.4.2 节。
Current
属性将继续返回它返回的最后一个值 - 这种情况下的行为是 explicitly undefined in MSDN . (我发誓这是为了抛出异常,但显然不是。)
这有意义吗? Dispose
不会“重置”迭代器(C# 迭代器 block 不支持 Reset
方法本身)。如果要再次迭代,需要再次调用GetEnumerator
。
现在,我记不清我在哥本哈根演讲中到底说了什么,如果其中有任何内容与视频显示的内容相悖,我深表歉意:)
关于c# - 了解迭代器 block 和 Dispose 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1872633/