名字'queen'在当前上下文中不存在-如何将Box附加到数据上
本文关键字:Box 数据 不存在 queen 上下文 名字 | 更新日期: 2023-09-27 18:14:05
不熟悉Windows窗体。我无法摆脱这个错误,我相信这是因为我没有button_1链接到我的女王类和/或我的实例"女王"。如果是这样,我如何在VS的设计视图的按钮属性中做到这一点?下面是一些相关的代码:
public Form1()
{
InitializeComponent();
Worker[] workers = new Worker[4];
workers[0] = new Worker(new string[] { "Nectar collector", "Honey manufacturing" });
workers[1] = new Worker(new string[] { "Egg care", "Baby bee tutoring" });
workers[2] = new Worker(new string[] { "Hive maintenance", "Sting patrol" });
workers[3] = new Worker(new string[] { "Nectar collector", "Honey manufacturing", "Egg care",
"Baby bee tutoring", "Hive maintenance", "Sting patrol" });
Queen queen = new Queen(workers);
}
private void button1_Click(object sender, EventArgs e)
{
if (queen.AssignWork(workerBeeJob.Text, (int)shifts.Value) == false)
MessageBox.Show("No workers are available to do the job '" + workerBeeJob.Text +
".' The queen bee says...");
else
MessageBox.Show("The job '" + workerBeeJob.Text + "' will be done in "
+ shifts.Value + " shifts. The queen bee says...");
}
class Queen
{
private Worker[] workers;
private int shiftNumber = 0;
public Queen(Worker[] workers)
{
this.workers = workers;
}
public bool AssignWork(string job, int numberOfShifts)
{
for (int i = 0; i < workers.Length; i++)
if (workers[i].DoThisJob(job, numberOfShifts))
return true;
return false;
}
问题在于变量的作用域。你的表单上没有一个叫做queen的成员(你在构造函数中创建的那个成员不属于表单),所以编译器不知道button1_Click
中的queen指的是谁。
我相信你打算使用你在构造函数中创建的皇后 ?也许你应该把皇后作为表单的一个属性,或者把引用保存在其他地方?
Queen queen; // class variable
和你的公共Form1()
queen = new Queen(workers);