如何允许单独的窗体使用另一个窗体上的对象列表
本文关键字:窗体 对象 列表 另一个 何允许 单独 | 更新日期: 2023-09-27 18:27:25
我在主窗体GUI
上有一个对象列表,而我可以使用foreach
循环访问该列表,例如foreach (Employee emp in employees)
这允许我访问列表中的员工。
在另一个表单上,我有一些代码要求它访问员工列表。
到目前为止,我已经尝试复制private List<Employee> employees;
但它给了我一个null引用异常,这显然意味着列表中没有任何内容被复制。
我会提供我的代码视图,这样你就可以有一些东西来建立你的解决方案:
代码主要形式
private List<Employee> employees;
public Form1()
{
InitializeComponent();
employees = new List<Employee>();
}
Employee e1 = new Employee(MemberJob.Employee, "Name", MemberSkills.CPlus);
添加了这段代码,以防我需要将一些变量发送到表单中
private void btnAddJob_Click(object sender, EventArgs e)
{
CreateAJob newForm2 = new CreateAJob();
newForm2.ShowDialog();
}
**附加表单代码**
private string _jobName = "";
private string _jobDifficulty = "";
private string _skillRequired = "";
private int _shiftsLeft = 0;
private List<Employee> employees; // tried to copy this over but there's nothing in it
public CreateAJob()
{
InitializeComponent();
}
public CreateAJob(string _jobName, string _skillRequired, int _shiftsLeft)
{
this._jobName = JobName;
this._skillRequired = SkillRequired;
this._shiftsLeft = ShiftsLeft;
}
private void Distribute(string _jobName, int _shiftsLeft, string _skillsRequired)
{
foreach (Employee emp in employees)
{
while (emp.Busy == true)
{
if (emp.Busy == false && emp.Skills.ToString() == _skillRequired)
{
emp.EmployeeWorkload = _jobName;
emp.ShiftsLeft = _shiftsLeft;
}
... additional code to finish method
创建另一个构造函数并像下面的一样传递Employee
列表
创建AJob表单:
internal CreateAJob(List<Employee> employees)
: this() // Make sure the normal constructor is executed
{
this.employees = employees;
}
主要形式:
private void btnAddJob_Click(object sender, EventArgs e)
{
CreateAJob newForm2 = new CreateAJob(employees);
newForm2.ShowDialog();
}