执行forloop时发生IndexOutOfRangeException

bil*_*lal 3 .net c#

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);
Run Code Online (Sandbox Code Playgroud)

发生异常IndexOutOfRangeException。为什么会发生这个异常,一切看起来都很好。

提前致谢。

解决方案

for (int i = 0; i < vowels.Length; i++)
{
char vowel = vowels[i];
query = query.Where (c => c != vowel);
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,这些代码有什么区别。请分享详细信息。

Ste*_*ven 6

问题是因为

  1. IEnumerable 是惰性的。
  2. 的值i未被捕获。

仅当您开始打印输出时才会实际评估查询.Where,此时i == 5会导致索引越界异常。


为了更清楚地显示发生的情况,下面是循环每次迭代的等效查询(请注意,query始终指原始查询):

i = 0;
query.Where(c => c != vowels[i]);

i = 1;
query.Where(c => c != vowels[i]).Where(c => c != vowels[i]);

i = 2;
query.Where(c => c != vowels[i]).Where(c => c != vowels[i]).Where(c => c != vowels[i]);

...
Run Code Online (Sandbox Code Playgroud)

看看所有查询如何引用相同的值i?在最后一次迭代之后,i又增加一次,这会导致循环停止。但现在i == 5,它不再是有效的索引了!