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

时间:2012-03-23 00:54:57

标签: c#

我在此行中收到对象引用错误: emp [count] .emp_id = int.Parse(parts [0]);

在此代码中

此程序从文件中读取并存储在对象数组

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 ";

        }

2 个答案:

答案 0 :(得分:9)

您需要初始化emp[count]

您可以通过添加以下内容来完成此操作:

foreach (string line in lines) 
{ 
    emp[count] = new employees();
    string[] parts = new string[4]; 
    //....
}

当您致电employees[] emp = new employees[emp_count];时,您会将emp初始化为employees的数组,其长度为emp_count

emp[0] = null;
emp[1] = null;
//etc.

emp中的每个元素也需要在使用之前进行实例化。

答案 1 :(得分:1)

emp[0]尚未初始化。类employees是可空类型,这意味着由它构成的数组被初始化为空。已初始化emp[count]new employees

BTW,“employees”是一个拥有单个员工的班级的奇怪名称。我认为它应该被称为Employee,那么声明你的数组就像这样:

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