C#(对象数组)对象引用未设置为对象的实例

6

我在这一行代码中遇到了对象引用错误:

emp[count].emp_id = int.Parse(parts[0]);

这是一个从文件中读取数据并存储在对象数组中的程序。

请注意,保留了 HTML 标签。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public class employees
    {
        public int emp_id;
        public string firstName;
        public string lastName;
        public double balance;
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        OpenFileDialog file = new OpenFileDialog();
        DialogResult result = file.ShowDialog();
        if (result == DialogResult.Cancel) return;

        string fileName = file.FileName;
        StreamReader reader = new StreamReader(fileName);

        string[] lines = File.ReadAllLines(fileName);
        int emp_count = lines.Count<string>();
        employees[] emp = new employees[emp_count];
        int count = 0;
        foreach (string line in lines)
        {
            string[] parts = new string[4];
            parts = line.Split(',');
            **emp[count].emp_id = int.Parse(parts[0]);**
            emp[count].firstName = parts[1];
            emp[count].lastName = parts[2];
            emp[count].balance = double.Parse(parts[3]);
            count++;
            txtGet.Text += emp[count].emp_id + " " + emp[count].firstName + " " + emp[count].lastName + " " + emp[count].balance + " \n ";

        }

抱歉,如何读取一个文件中的数据并将其存储在对象数组中,然后将此数据写入新文件?string path = "D:\new.txt"; StreamWriter writer; writer = File.CreateText(path); string record = " "; for (int i = 0; i < emp_count; i++) { record+= emp[0].emp_id + "," + emp[1].firstName + "," + emp[2].lastName + "," + emp[3].balance + "\n"; } writer.WriteLine(record); writer.Close(); - Beginner
2个回答

12

你需要将emp[count]初始化为某个值。

你可以通过添加以下代码来实现此操作:

foreach (string line in lines) 
{ 
    emp[count] = new employees();
    string[] parts = new string[4]; 
    //....
}
当您调用employees[] emp = new employees[emp_count];时,您将emp初始化为一个长度为emp_countemployees数组。
emp[0] = null;
emp[1] = null;
//etc.

在使用之前,emp中的每个元素都需要先实例化。


2

emp[0]没有被初始化。类employees是可空类型,这意味着由它制作的数组被初始化为null。将emp[count]初始化为new employees

顺便说一下,“employees”是一个持有单个员工的类的奇怪名称。我认为它应该被称为Employee,然后像这样声明你的数组才有意义:

 `Employee[] employees = new Employee[emp_count];`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接