为什么我的数组抛出超出范围的异常错误?

Sku*_*uta 1 c# arrays

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

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

例外:

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()
Run Code Online (Sandbox Code Playgroud)

物品声明:

获取字符串数组的函数:

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);
Run Code Online (Sandbox Code Playgroud)

Sho*_*og9 6

你有一个直的二维数组.长度为您提供数组中元素总数,但您使用它来计算单个维度的索引.你想要的是:

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