如何允许单独的表单在另一个表单上使用对象列表?

How to allow seperate form to use list of objects on another?

我的主窗体上有一个对象列表 - GUI - 虽然我可以使用 foreach 循环访问该列表,例如 foreach (Employee emp in employees) 这允许我访问列表中的员工。

在另一种形式上,我有一些代码需要它来访问员工列表。

到目前为止,我已经尝试复制 private List<Employee> employees; 但它给了我一个空引用异常,显然意味着列表中没有任何内容被复制。

我将提供我的代码的视图,以便您可以根据您的解决方案:

代码 主窗体

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 列表

CreateAJob 表单:

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();
}