0

Windows 窗体的新手。我无法摆脱这个错误,我相信这是因为我没有将 button_1 链接到我的 Queen 类和/或我的实例“queen”。如果是这种情况,我该如何在 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;
        }
4

2 回答 2

2

问题是变量的范围。您的表单上没有一个名为queen的成员(您在构造函数中创建的成员不属于该表单),因此编译器不知道其中的queenbutton1_Click指的是谁。

我相信你打算使用你在构造函数中创建的女王?也许你应该让那个女王成为表单的属性,或者将引用保留在其他地方?

于 2013-05-17T22:18:39.540 回答
0
Queen queen; // class variable

在你的公共 Form1()

queen = new Queen(workers);
于 2013-05-17T23:24:15.837 回答