首页 > 解决方案 > 找不到“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--|

标签: c#arraysindexoutofrangeexception

解决方案


if (linesRead[i][0] == '5')如果一行为空,将触发此错误。

尝试

if (linesRead[i].StartsWith("5"))

反而。


推荐阅读