假设有如下代码:
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)); } }
输出结果是:
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都是需要迭代的。