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

C#如何访问从CSV读取后存入List的Account类对象的属性?

问题根源

你遇到的报错核心是变量作用域问题:你在ReadAccounts方法内定义的accounts是局部变量,它的生命周期仅局限于ReadAccounts方法内部,方法执行完成后该变量就会被销毁,因此你在Form2_Load方法中无法访问到这个变量,才会出现报错。

修复方案

核心是把accounts提升为Form2类的成员变量,让整个类的方法都可以访问,同时可以针对银行账户的业务场景做一些代码健壮性优化,修改后的完整代码如下:

class Account
{
    // 建议用公开属性代替公开字段,符合C#编码规范
    public string CustomerName { get; set; }
    public string PIN { get; set; }
    // 金额不要用double,存在浮点精度误差,改用decimal类型更适合金融场景
    public decimal Balance { get; set; }

    public Account(string rowData)
    {
        string[] data = rowData.Split(',');
        // 新增数据合法性校验,避免数组越界、格式转换失败报错
        if (data.Length < 3) 
            throw new ArgumentException("账户数据格式不正确");
        
        this.CustomerName = data[0].Trim();
        this.PIN = data[1].Trim();
        this.Balance = Convert.ToDecimal(data[2].Trim());
    }
}

public partial class Form2 : Form
{
    // 提升为类的私有成员变量,所有实例方法都可以访问
    private List<Account> _accounts = new List<Account>();

    public Form2()
    {
        InitializeComponent();
    }

    public void ReadAccounts()
    {
        string[] csvLines = System.IO.File.ReadAllLines("Accounts.csv");
        // 每次读取前清空旧数据,避免重复累加
        _accounts.Clear();

        for (int i = 1; i < csvLines.Length; i++)
        {
            try
            {
                Account acc = new Account(csvLines[i]);
                _accounts.Add(acc);
            }
            catch (Exception ex)
            {
                // 可自定义异常处理逻辑,比如跳过错误行、弹窗提示等
                MessageBox.Show($"第{i+1}行数据解析失败:{ex.Message}");
            }
        }
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        ReadAccounts();
        // 现在可以正常访问_accounts里的对象属性了
        for (int i = 0; i < _accounts.Count; i++)
        {
            // 示例:获取当前账户的用户名和余额
            string name = _accounts[i].CustomerName;
            decimal balance = _accounts[i].Balance;
            // 你的业务逻辑
        }

        // 也可以用foreach遍历更简洁
        foreach (var account in _accounts)
        {
            Console.WriteLine($"客户:{account.CustomerName},余额:{account.Balance:C}");
        }
    }
}
额外优化建议
  • 如果CSV存在带逗号的字段(比如用户名里包含逗号),直接用Split方法拆分数据会出错,复杂场景下可以用专门的CSV解析组件处理
  • 敏感数据比如PIN不要明文存在CSV里,建议加密存储
  • 文件路径建议用绝对路径,避免运行时找不到文件,比如可以用Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Accounts.csv")获取程序运行目录下的CSV文件路径

内容的提问来源于stack exchange,提问作者Herman Kapange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:57:04