【问题标题】:ArgumentOutOfRangeException at Calling Index调用索引处的 ArgumentOutOfRangeException
【发布时间】:2014-12-21 13:03:32
【问题描述】:

我遇到了一个非常烦人的错误。

我的以下代码是我所拥有的(1 小时前同样有效)

        using (StreamReader reader = new StreamReader(dir + fileDAT))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                line = reader.ReadLine();
                if (line.Substring(0,5) == "\tVNUM\t")
                {
                    vnum = Convert.ToInt32(line.Substring(6));
                    Console.ReadLine(); 
                    Console.WriteLine(line); // Write to console.
                }

            }
        }

但现在它在 if (line.Substring(0,5) == "\tVNUM\t") 行抛出 ArgumentOutOfRangeException

你知道如何解决这个问题吗? “\t”有多少索引?

【问题讨论】:

  • 出现异常时line的值是多少?这会告诉你哪里出了问题。
  • 它是 "\tVNUM\t0" .. 但现在它可以工作了。见下文

标签: c# indexing substring


【解决方案1】:

line 的长度可能少于 5 个字符。
将您的 if 替换为以下内容:

if (line.Length >= 5 && line.Substring(0,5) == "\tVNUM\t")

\t 字符是一个字符,所以它的长度是1 字符。

顺便说一句,您确定每次迭代都需要读取两次行吗?我的意思是以下代码部分:

while ((line = reader.ReadLine()) != null)  // 1st read
{
    line = reader.ReadLine();  // 2nd read

编辑
字符串 "\tVNUM\t"6 字符长,你知道的。将其与 5 个字符长度的子字符串进行比较是没有任何意义的。

【讨论】:

  • 感谢您的回答。字符串行长 7 个字符,但如果我用你的代码替换我的代码,它只会跳过该过程..
  • 是的。你说得对。它是多余的,但我只放了两次来测试它
  • 这是因为字符串"\tVNUM\t"6 字符长。
  • 啊,是的。但是读取的行是 7 个字符长 ("\tVNUM\t0") 但我认为在粘贴代码并使用索引后,它现在可以工作了。
  • 只需将5 替换为if 中的6 即可比较6 个字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
相关资源
最近更新 更多