gpt4 book ai didi

c# - 执行forloop时出现IndexOutOfRangeException

转载 作者:行者123 更新时间:2023-11-30 20:44:56 26 4
gpt4 key购买 nike

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);

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

提前致谢。

解决方案

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

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

最佳答案

问题是因为

  1. IEnumerables 是惰性的。
  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]);

...

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

关于c# - 执行forloop时出现IndexOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28758375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com