You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#导入CSV生成员工薪资记录代码输出null故障排查求助

问题原因

你的代码存在以下几处逻辑错误:

  • 未跳过CSV表头:代码第一次调用reader.ReadLine()读取的是CSV的表头行,直接尝试将表头字段EmployeeId转为int类型会抛出格式异常,是运行后输出为null的核心原因。
  • Visa、YearToDate变量未重置:两个变量在循环外声明,若前一个员工有Visa/YearToDate值,后一个无对应值的员工会错误沿用前一个的数值。
  • 固定长度数组逻辑错误:Hours和Rate数组固定长度为10,一是单员工记录超过10条会触发数组越界,二是员工记录不足10条时,你传入CreatePayRecord的数组会包含大量默认0值,导致计算结果错误。
  • 空值判断缺失:首次读取文件内容后未做空判断就直接调用Split(),空文件会触发空引用异常,同时StreamReader未手动释放,会导致文件句柄泄漏。

修正代码(兼容无第三方类库要求)

全程只用C#基础原生API,无额外类库依赖:

public static List<PayRecord> ImportPayRecords(string file)
{
    List<PayRecord> payRecords = new List<PayRecord>();
    StreamReader reader = new StreamReader(file);
    try
    {
        // 跳过表头行
        string record = reader.ReadLine();
        if (record == null)
        {
            return payRecords;
        }

        int EmployeeId;
        int i = 0;
        int id;
        string[] strArr;
        // 初始化数组长度为10,后续不够自动扩容
        double[] Hours = new double[10];
        double[] Rate = new double[10];

        record = reader.ReadLine();
        while (record != null)
        {
            strArr = record.Split(',');
            EmployeeId = int.Parse(strArr[0]);
            // 每个员工单独初始化签证和累计年薪字段,避免复用前值
            string Visa = "";
            string YearToDate = "";
            if (strArr[3] != "")
            {
                Visa = strArr[3];
                YearToDate = strArr[4];
            }

            id = EmployeeId;
            while (record != null && id == int.Parse(strArr[0]))
            {
                // 数组容量不足时自动扩容2倍
                if (i >= Hours.Length)
                {
                    Array.Resize(ref Hours, Hours.Length * 2);
                    Array.Resize(ref Rate, Rate.Length * 2);
                }
                Hours[i] = double.Parse(strArr[1]);
                Rate[i] = double.Parse(strArr[2]);
                i++;
                record = reader.ReadLine();

                if (record != null)
                {
                    strArr = record.Split(',');
                }
            }
            
            // 截取实际有效长度的数组,避免传入多余0值
            double[] validHours = new double[i];
            double[] validRate = new double[i];
            Array.Copy(Hours, validHours, i);
            Array.Copy(Rate, validRate, i);
            
            PayRecord rec = CreatePayRecord(EmployeeId, validHours, validRate, Visa, YearToDate);
            payRecords.Add(rec);
            
            // 重置计数器和数组
            i = 0;
            Array.Clear(Hours, 0, Hours.Length);
            Array.Clear(Rate, 0, Rate.Length);
        }
    }
    finally
    {
        // 手动释放文件流资源
        reader.Dispose();
    }
    return payRecords;
}

内容的提问来源于stack exchange,提问作者Alex Jey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:27:05