LINQ中的 Deffered Execution

LINQ的延迟执行:


 1 
 2 IEnumerable<char> query = "Not what you might expect";
 3 foreach (char vowel in "aeiou")
 4     {
 5              query = query.Where (c => c != vowel);
 6          }
 7 
 8 //query结果为字符串"Not what yo might expect"
 9 
10 
11 IEnumerable<char> query = "Not what you might expect";
12 foreach (char vowel in "aeiou")
13     {
14              char temp=vowel;
15              query = query.Where (c => c != temp);
16          }
17 
18 
19 
20 //query结果为"Nt wht y mght xpct"


为什么会这样,因为IEnumberable的Where方法是延迟执行的:

此方法通过使用延迟执行实现。即时返回值为一个对象,该对象存储执行操作所需的所有信息。只有通过直接调用对象的 GetEnumerator 方法或使用 Visual C# 中的 foreach(或 Visual Basic 中的 For Each)来枚举该对象时,才执行此方法表示的查询。

因此第一个例子中,Where中保存了一个vowel的引用,当执行查询的时候,foreach已经执行完,此时vowel的值为‘u’,故有此结果。

第2个例子中,Where保存的是temp的引用,可是因为foreach每次循环都会声明temp并赋值,因此实际有5个temp的值被保存,当foreach执行完之后,再调用其他能触发查询的方法便得到的是如上结果。相当于委托链有5个方法并以此执行:

1 query = query.Where (c => c != 'a');
2 query = query.Where (c => c != 'e');
3 query = query.Where (c => c != 'i');
4 query = query.Where (c => c != 'o');
5 query = query.Where (c => c != 'u');

posted on 2009-07-21 21:04  MoonWalker  阅读(184)  评论(0编辑  收藏  举报

导航