首页 > 解决方案 > 捕获的变量 IndexOutOfBounds

问题描述

我有两个代码循环片段,后者按预期工作,而前者抛出异常。为什么 foreachwhilefor循环不起作用?它源于什么?

IEnumerable<char> query = "Not what you might expect";

query = query.Where (c => c != 'a');
query = query.Where (c => c != 'e');
query = query.Where (c => c != 'i');
query = query.Where (c => c != 'o');
query = query.Where (c => c != 'u');

foreach (char c in query) Console.Write (c);  // Nt wht y mght xpct

For 循环异常

IEnumerable<char> query = "Not what you might expect";
string vowels = "aeiou";

for (int i = 0; i < vowels.Length; i++)
  query = query.Where (c => c != vowels[i]);

foreach (char c in query) Console.Write (c);

foreach代码,

foreach (char vowel in vowels)
  query = query.Where (c => c != vowel);

foreach (char c in query) Console.Write (c);

标签: c#.netlinqienumerable

解决方案


好吧,Linq使用惰性(延迟执行),所以你有:

// Just a declaration, query doesn't execute
for (int i = 0; i < vowels.Length; i++)
  query = query.Where (c => c != vowels[i]);

// now, after the for loop, i is equal to vowels.Length

// Here, query executes with current i value, i == vowels.Length
// And you have an out of range exception
foreach (char c in query) Console.Write (c);

推荐阅读