本文发表在 rolia.net 枫下论坛程序如下:
static void Main(string[] args)
{
foreach (string num in getNumbers())
{
Console.WriteLine("I am geting numbers: " + num.ToString());
}
}
static IEnumerable<string> getNumbers()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(i.ToString());
yield return i.ToString();
}
}
打印出的结果是这个样子
0
I am geting numbers: 0
1
I am geting numbers: 1
2
I am geting numbers: 2
很明显,yield返回一个数,然后主程序处理一下,然后yield在返回一个数,主程序再处理一下.......etc
如果改成这个样子
static void Main(string[] args)
{
foreach (string num in getNumbers().ToArray())
{
Console.WriteLine("I am geting numbers: " + num.ToString());
}
}
static IEnumerable<string> getNumbers()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(i.ToString());
yield return i.ToString();
}
}
结果就会变为:
0
1
2
I am geting numbers: 0
I am geting numbers: 1
I am geting numbers: 2
哈哈,因为我加了getNumbers().ToArray(),这时系统就会显示的把getNumbers()的结果变为一个存储在内存中的Array,所以必须先要遍历getNumbers(),就会形成上面的结果更多精彩文章及讨论,请光临枫下论坛 rolia.net
static void Main(string[] args)
{
foreach (string num in getNumbers())
{
Console.WriteLine("I am geting numbers: " + num.ToString());
}
}
static IEnumerable<string> getNumbers()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(i.ToString());
yield return i.ToString();
}
}
打印出的结果是这个样子
0
I am geting numbers: 0
1
I am geting numbers: 1
2
I am geting numbers: 2
很明显,yield返回一个数,然后主程序处理一下,然后yield在返回一个数,主程序再处理一下.......etc
如果改成这个样子
static void Main(string[] args)
{
foreach (string num in getNumbers().ToArray())
{
Console.WriteLine("I am geting numbers: " + num.ToString());
}
}
static IEnumerable<string> getNumbers()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(i.ToString());
yield return i.ToString();
}
}
结果就会变为:
0
1
2
I am geting numbers: 0
I am geting numbers: 1
I am geting numbers: 2
哈哈,因为我加了getNumbers().ToArray(),这时系统就会显示的把getNumbers()的结果变为一个存储在内存中的Array,所以必须先要遍历getNumbers(),就会形成上面的结果更多精彩文章及讨论,请光临枫下论坛 rolia.net