这是我的C#代码。
public class Person
{
public List<Employee> empDetails;
}
public class Employee
{
public string Id { get; set; }
public string Name { get; set; }
public string proj { get; set; }
public string No { get; set; }
}
//This method is defined in a service
public void ReadFiles()
{
DirectoryInfo dir = new DirectoryInfo("E:/NewFolder/NewFiles");
FileInfo[] files = dir.GetFiles("*.*");
Person p = new Person();
Employee e = new Employee();
foreach (FileInfo f in files)
{
XmlDocument doc = new XmlDocument();
doc.Load(f.FullName);
e.empId = doc.GetElementsByTagName("Id")[0].InnerText;
e.empName = doc.GetElementsByTagName("Name")[0].InnerText;
e.empSeatNo = doc.GetElementsByTagName("No")[0].InnerText;
e.projGroup = doc.GetElementsByTagName("Grp")[0].InnerText;
p.empDetails.Add(e); //Here I get the error "Object reference not set to an instance of an object"
}
}
任何帮助表示赞赏。
答案 0 :(得分:2)
Person类不会初始化empDetails
。大多数人都会在构造函数中执行此操作。
public class Person
{
public Person()
{
empDetails = new List<Employee>();
}
public List<Employee> empDetails { get; private set; }
}
此外,您对属性名称的情况也不符合惯例。 Normaly它会EmpDetails甚至更好的EmployeeDetails。
答案 1 :(得分:2)
永远不会分配列表;这应该有效:
public class Person
{
private readonly List<Employee> empDetails = new List<Employee>();
public List<Employee> EmploymentDetails { get { return empDetails; } }
}
(并访问.EmploymentDetails
,即p.EmploymentDetails.Add(e);
)