#.net #c#-4.0
#.net #c #-4.0
Вопрос:
Это мой код на 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"
}
}
Любая помощь приветствуется.
Ответ №1:
Класс Person не инициализируется empDetails
. Большинство людей сделают это в конструкторе.
public class Person
{
public Person()
{
empDetails = new List<Employee>();
}
public List<Employee> empDetails { get; private set; }
}
Также ваш случай с именами свойств не соответствует соглашению. Обычно это были бы EmpDetails или даже лучше EmployeeDetails.
Ответ №2:
Список никогда не присваивается; это должно сработать:
public class Person
{
private readonly List<Employee> empDetails = new List<Employee>();
public List<Employee> EmploymentDetails { get { return empDetails; } }
}
(и доступ .EmploymentDetails
, т. е. p.EmploymentDetails.Add(e);
)