如何将类中的信息添加到列表中
本文关键字:添加 列表 信息 | 更新日期: 2023-09-27 18:27:20
如果我有两个这样的类:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> employees { get; set; }
}
public class Employee
{
public string Name { get; set; }
public string Job { get; set; }
public string Date { get; set; }
}
然后如果我这样做:
var departments = new List<Department>();
Department d = new Department
{
Id = 1,
Name = "Depart1",
};
Department d2 = new Department
{
Id = 2,
Name = "Depart2",
};
departments.Add(d);
departments.Add(d2);
如何使用foreach循环将添加到Department类中的员工列表?当我这样做时:
foreach(Department dmt in departments)
{
Employee worker = new Employee
{
Name = "Steve",
Job = "Cleanup",
Date = "Today",
};
dmt.employees.Add(worker );
}
我没有得到任何构建错误,但没有添加任何内容。有什么建议吗?
您没有实例化employees
属性。将您的类定义更改为:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> employees { get; set; }
public Department()
{
employees = new List<Employee> ();
}
}
或者,如果您不想使用构造函数来实例化employees
属性,那么在尝试将Employee
对象添加到List<Employee>
之前,您只需要确保这样做。
您需要在Department类中初始化公共属性员工
在这种情况下,您可以在Department实例的构造函数中执行此操作。
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> employees { get; set; }
public Department()
{
employees = new List<Employee>();
}
}
像这样尝试
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> employees { get; set; }
public Department()
{
employees = new List<Employee>();
}
}
foreach(Department dmt in departments)
{
dmt.employees.Add( new Employee () {
// InterestedID = ((int)dataReader["JobId"]),
Name = "Steve",
Job = "Cleanup",
Date = "Today",
});
}
我会这样设计我的类,使Employees List只读:
public class Department
{
private readonly List<Employee> _employees = new List<Employee>();
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> employees { get { return this._employees; }}
}