c# - 捕获的变量 IndexOutOfBounds
问题描述
我有两个代码循环片段,后者按预期工作,而前者抛出异常。为什么 foreach
whilefor
循环不起作用?它源于什么?
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);
解决方案
好吧,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);
推荐阅读
- visual-studio-code - VS Code 是否有扩展来替换标题栏?
- python - 请求错误:未找到连接适配器
- python - 如何使用与功能相关的颜色图绘制立方体或平行六面体
- python - 如何使用 django_oauth_toolkit 从 refresh_token 获取新的 access_token?
- filter - 标准外设库中的 STM8A CAN 过滤
- javascript - 点击html标签后Javascript不起作用?
- php - 刷新页面时如何自动清除缓存?
- azure - 接收双更新通知的 Azure IoT 设备
- excel - 查找包含波浪号的文本
- swift - 在 Swift 中使用重定向 url 时的 ATS 策略问题