我正在观看Jon Skeet的哥本哈根C#谈话视频,我最终得到了这段代码.
问题:
代码打印完成后发生了什么.我的意思是为什么会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
Run Code Online (Sandbox Code Playgroud)
调用MoveNext()
只是在false
没有做任何其他事情的情况下返回,因为你已经处理了迭代器.由C#编译器构建的状态机将进入"后"状态,并保持在那里.有关详细信息,请参阅C#3规范的第10.14.4.2节.
该Current
属性将继续返回它返回的最后一个值 - 在MSDN中显式未定义此情况下的行为.(我本可以发誓这是为了抛出异常,但显然不是.)
那有意义吗?Dispose
不会"重置"迭代器(并且Reset
C#迭代器块不支持该方法本身).如果您想再次迭代,则需要GetEnumerator
再次调用.
现在,我不记得我在哥本哈根会谈中所说的话,如果其中任何一个看起来与视频显示的内容相反,那么道歉:)
归档时间: |
|
查看次数: |
815 次 |
最近记录: |