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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9832765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:49:58  来源:igfitidea点击:

C# (Array of object) object reference not set to an instance of an object

c#

提问by Beginner

I am getting the object reference error in this line: emp[count].emp_id = int.Parse(parts[0]);

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

in this code

在这段代码中

this program to read from file and store in array of object

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

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

        }

采纳答案by DaveShaw

You need to initialise emp[count]to something.

你需要初始化emp[count]一些东西。

You can do this by adding the following:

您可以通过添加以下内容来做到这一点:

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

When you call employees[] emp = new employees[emp_count];you initilise empto an array of employeeswith the length of emp_count.

当您调用employees[] emp = new employees[emp_count];initiliseemp到一个employees长度为emp_count.

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

Each element inside empalso needs to be instantiated before you can use it.

里面的每个元素emp也需要先实例化才能使用。

回答by Diego

emp[0]has not been initialized. Class employeesis a nullable type, which means arrays made of it are initialized to nulls. Initialize emp[count]to new employees.

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

BTW, "employees" is a strange name for a class that holds a single employee. I think it should be called Employee, then it makes sens to declare your array like this:

顺便说一句,“ employees”对于一个包含单个员工的类来说是一个奇怪的名字。我认为它应该被调用Employee,然后像这样声明你的数组是有意义的:

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