Contents

假设有如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static IEnumerable<int> getInt()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("get " + i);
yield return i;
}

}

static void Main(string[] args)
{
for (int i = 0; i < getInt().Count(); i++)
{
Console.WriteLine(getInt().ElementAt(i));
}
}

输出结果是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
get 0
get 1
get 2
get 0
0
get 0
get 1
get 2
get 0
get 1
1
get 0
get 1
get 2
get 0
get 1
get 2
2
get 0
get 1
get 2

呵呵,说明了.Count()和ElementAt都是需要迭代的。

Contents