c# - 找不到“IndexOutOfRangeException”的原因
问题描述
我遇到了 indexOutOfBounds 异常的奇怪问题。我需要读取数组中每个字符串的第一个字符。
我在第 5 行 (linesRead[i][0]) 出现异常。对我来说最奇怪的是,当我尝试添加用于调试 Console.WriteLine(linesRead[0][0]) / Console.WriteLine(linesRead[linesRead.Length-1][0]) 的行时,它工作得很好。
string[] linesRead = System.IO.File.ReadAllLines(@"test.txt"); //Just a bunch of lines
for (int i = 0; i < linesRead.Length; i++)
{
if (linesRead[i][0] == '5')
{
//Do stuff
}
}
The text inside of test.txt:
5|f-----g-----c---g-----a---|
6|--c-----------------------|
5|---Aa-f-----g-----c-------|
5|------ccdf-ff-----g-----c-|
6|--------------c-----------|
5|--g-----a------Aa-f-----g-|
5|----c-------------ccdf-f--|
解决方案
if (linesRead[i][0] == '5')
如果一行为空,将触发此错误。
尝试
if (linesRead[i].StartsWith("5"))
反而。
推荐阅读
- python - 当敌人被杀死时,Explosions Sprite Despears Way to Fast 如何解决这个问题?
- c++ - 是否可以创建一个从不同类调用函数的线程?
- python - Pygame 中的曲线
- docker - 命令适用于 heroku 命令行,但不适用于推送的 docker 映像
- c++ - 如何在另一个函数中使用返回值作为参数?
- javascript - 如何在 getDerivedStateFromProps 中使用 setInterval
- python - sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedColumn) 列不存在
- java - 如何使用二维数组中的数据填充 TableView?
- javascript - FormData 在 Ajax 和 Wordpress 表单中返回未定义
- android - ImageButton 三角形背景