【问题标题】:Why is my array throwing Out of Range Exception Error?为什么我的数组抛出超出范围异常错误?
【发布时间】:2009-04-03 23:59:22
【问题描述】:

为什么下面的代码会抛出异常?

for (int i = 0; i <= Items.Length-1; i++)
{
    Console.WriteLine(Items[i,1]);
}

例外:

System.IndexOutOfRangeException was unhandled
  Message="Index was outside the bounds of the array."
  Source="Es"
  StackTrace:
       at Es.Program.Main(String[] args) in C:\Users\Fero\Documents\Visual Studio 2005\Projects\Es\Es\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

物品声明:

获取字符串数组的函数:

static string[,] ReadFromFile(string filename, int rowsF)
{
    StreamReader SR;
    string S;
    string[] S_split;

    SR = File.OpenText(filename);
    S = SR.ReadLine();

    string[,] myItems = new String[rowsF, 2];
    int row_number = 0;
    while (S != null)
    {
        S_split = S.Split('"');
        //temp_items[row_number,0] = 
        myItems[row_number,0] = S_split[1];
        myItems[row_number,1] = S_split[2];

        row_number++;
        S = SR.ReadLine();
    }
    SR.Close();
    return myItems;
}

string[,] Items = ReadFromFile(myFile, rowsF);

【问题讨论】:

  • 数组声明是什么样子的?
  • 可以包含Items的声明吗?
  • 我已经添加了一些东西来发布
  • 第 119 行是 (Console.WriteLine) ?
  • 如果够短,我们能看到输入文件吗?

标签: c# arrays


【解决方案1】:

你有一个直的二维数组。 Length 为您提供数组中的total number of elements,但您使用它来计算单个维度的索引。你想要的是:

for (int i = 0; i < Items.GetLength(0); i++)
{
    Console.WriteLine(Items[i,1]);
}

【讨论】:

    【解决方案2】:

    检查 Items[i] 的长度。它似乎是一个 2D 数组,而且它显然不是 null,因为你会得到一个不同的异常,所以它可能只是 Items[i] 处的一个空数组,或者只包含一个项目。

    检查:

    Items[i] == null
    Items[i].Length > 0
    

    编辑:您的附加代码有所帮助。当您拆分字符串以初始化项目时,对于给您带来麻烦的项目,请检查您在索引 1 处存储的内容。除此之外,我看不出它有什么问题。

    【讨论】:

    • 数组中有两列。
    【解决方案3】:

    据我所知,其中一行不符合您要求的格式的可能性很小。看起来您正在检索基于引号 (") 分隔的文本,而 S_split[] 可能并不总是具有这些字段数。

    例如,文件末尾的空行将触发异常。

    【讨论】:

      【解决方案4】:

      因为Items[i].Length 是,所以抛出异常

      在尝试访问Items[i,1]之前,您需要检查(Items[i].Length &gt;= 2)

      【讨论】:

      • 我不太明白你在这里的意思。什么“项目”??
      • 对不起,是 Items(你拥有的二维数组)
      • 第二个维度足够大,它是第一个维度索引给出异常。 Items.GetLength(0)
      【解决方案5】:
          S_split = S.Split('"');
          //temp_items[row_number,0] = 
          myItems[row_number,0] = S_split[1];
          myItems[row_number,1] = S_split[2];
      

      您确定不想要 S_Split[0] 和 S_Split[1]?

      应该看到输入文件。

      【讨论】:

      • 不,我检查了值.. 我的 .dat 文件包含“某事”xxxxxx,我需要得到某事和 xxxxx
      猜你喜欢
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2016-04-23
      相关资源
      最近更新 更多