我在这一行中收到对象引用错误:
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 ";
}
你需要初始化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
还需要先实例化才能使用它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)