【问题标题】:How to allow seperate form to use list of objects on another?如何允许单独的表单在另一个表单上使用对象列表?
【发布时间】:2015-12-20 15:34:11
【问题描述】:

我的主窗体上有一个对象列表 - 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

【问题讨论】:

  • 您似乎认为创建与另一个员工列表同名的新员工列表涉及某种副本。这不是真的。您应该将第一个列表传递给第二个表单,并将在 CreateAJob 表单中声明的​​变量分配给 Main 表单的同一实例

标签: c# winforms oop generic-list


【解决方案1】:

创建另一个构造函数并像这样传递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();
}

【讨论】:

  • 它说“不一致的可访问性:参数类型List&lt;Employee&gt;` is less accessible than method `CreateAJob.CreateAJob(List&lt;Employee&gt;) 我假设这是因为我将某些内容设为私有但我不想公开列表
  • @DannyWatson 很可能是您在internal 中的Employee 课程。在这种情况下,您也需要创建新的构造函数 internal,如更新的答案所示。
猜你喜欢
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
相关资源
最近更新 更多