首页 > 解决方案 > 从文件中读取时,索引超出了数组的范围

问题描述

我希望你们所有人都有美好的一天。所以我修复了我的程序的一个错误,但还有另一个错误:/

所以这是我创建并从文件中读取数据的代码:

  void ReadData(string fileName, Branch[] branches)
    {
        string shopsName = null;
        using (StreamReader reader = new StreamReader(@fileName))
        {
            string line = null;
            line = reader.ReadLine();
            if (line != null)
            {
                shopsName = line;
            }
            Branch tempBranches = TempBranch(branches, shopsName);
            string address = reader.ReadLine();
            string phoneNumber = reader.ReadLine();
            while (null != (line = reader.ReadLine()))
            {
                string[] values = line.Split(';');
                string facturer = values[0];
                string model = values[1];
                double capacity = double.Parse(values[2]);
                string energyClass = values[3];
                string assemblyType = values[4];
                string color = values[5];
                string attribute = values[6];
                double cost = double.Parse(values[7]);
                Fridges fridge = new Fridges(facturer, model, capacity, energyClass, assemblyType, color, attribute, cost);
                tempBranches.fridges.AddFridge(fridge);
            }
        }

还有我使用 TempBranch 方法的代码。错误在这一行:if (branches[i].ShopsName == shopsName)。希望你能帮助我,因为我昨天试图修复这个问题 30 分钟,但它仍然没有工作:D

private static Branch TempBranch(Branch[] branches, string shopsName)
    {
        for (int i = 0; i < MaxNumberOfFridges; i++)
        {
            if (branches[i].ShopsName == shopsName)
            {
                return branches[i];
            }
        }
        return null;
    }

标签: c#

解决方案


如果你用它替换MaxNumberOfFridgesbranches.Length只会尝试找到一个在数组Branch范围内的。branches它不起作用的原因是因为您试图访问一个大于Length数组的索引。


推荐阅读