C# readEmployees方法代码补全及索引行运行异常求助
问题修复方案
你当前代码的索引赋值异常、运行加载失败,本质是缺两个核心部分:employee类型定义、员工存储集合的正确初始化,以下是可直接运行的补全内容。
1. 补全employee结构体
完全匹配你现有代码的构造函数传参顺序,直接放到和readEmployees同个命名空间下即可:
public struct employee { public int Id; public string FirstName; public string LastName; public double Income; public double KiwiSaverRate; // 对应当前代码调用的五参数构造方法 public employee(int id, string firstName, string lastName, double income, double kiwiSaverPercentage) { Id = id; FirstName = firstName; LastName = lastName; Income = income; KiwiSaverRate = kiwiSaverPercentage; } }
2. 修复索引报错的核心修改
最稳妥的方式是替换成自动扩容的List<employee>,不需要手动维护index计数,从根源避免索引错误。对应修改后的完整方法+静态字段声明如下:
// 你的静态工具类,类名替换成你项目里实际的类名即可 public static class EmployeeTool { // 全局静态员工存储集合,替换原有的定长数组 public static List<employee> employees = new List<employee>(); public static void readEmployees() { // 每次加载前清空旧数据,避免重复读取 employees.Clear(); // 用using块自动释放流资源,不需要手动调用Close,异常时也不会占用文件 using (FileStream fileStream = new FileStream(@"C:\Users\Public\TestFolder\Test.txt", FileMode.Open, FileAccess.Read)) using (StreamReader streamReader = new StreamReader(fileStream)) { streamReader.BaseStream.Seek(0, SeekOrigin.Begin); string line; while ((line = streamReader.ReadLine()) != null) { // 跳过空行,避免拆分后字段数不足 if (string.IsNullOrWhiteSpace(line)) continue; // 拆分时自动忽略连续空格产生的空条目 string[] empFields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); // 校验行数据完整性,避免缺字段时索引越界 if (empFields.Length < 5) { Console.WriteLine($"跳过无效数据行:{line},字段数量不足5个"); continue; } int employeeId = int.Parse(empFields[0]); string employeeFirstName = empFields[1]; string employeeLastName = empFields[2]; double employeeIncome = double.Parse(empFields[3]); double employeeKiwiSaverPercentage = double.Parse(empFields[4]); employee emp = new employee(employeeId, employeeFirstName, employeeLastName, employeeIncome, employeeKiwiSaverPercentage); // 列表直接Add即可,不需要手动维护index变量 employees.Add(emp); } } } }
前置校验要求
你的数据源Test.txt必须符合以下格式,否则还是会抛解析异常:
- 每行对应1条员工数据
- 字段用单个/多个空格分隔,顺序固定为:
员工ID 名 姓 税前收入 KiwiSaver缴纳比例 - ID、收入、缴纳比例字段必须是合法数字,不能带货币符号、百分号等非数字字符
如果你坚持用数组而不是List存储,必须在读取前先计算有效数据行数初始化数组长度,否则一定会出现索引越界:
// 数组初始化方式(不推荐) int validLineCount = File.ReadLines(@"C:\Users\Public\TestFolder\Test.txt").Count(l => !string.IsNullOrWhiteSpace(l)); employees = new employee[validLineCount];
内容的提问来源于stack exchange,提问作者Charlee Kenneth
相关产品推荐
相关产品推荐

