创建Form1的对象会导致堆栈溢出

时间:2014-10-16 03:15:55

标签: c# class object instance stack-overflow

我在Form1中有一个标签,我正在尝试修改。这是我的代码:

namespace asst5
{
    public partial class Form1 : Form
    {
        Robot robot1 = new Robot();
        public Form1()
        {
            InitializeComponent();
            label2.Location = new Point(100,100);
            label1.Text = label2.Location.ToString();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label2.Text = "↑";
            robot1.direction = 1;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            label2.Text = "↓";
            robot1.direction = 2;
        }

        private void east_Click(object sender, EventArgs e)
        {
            label2.Text = "→";
            robot1.direction = 4;
        }

        private void west_Click(object sender, EventArgs e)
        {
            label2.Text = "←";
            robot1.direction = 3;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            robot1.speed = 1;
            robot1.move();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            robot1.speed = 10;
            robot1.move();
        }
    }

    public class Robot
    {
        Form1 frm1 = new Form1();
        public int direction = 1; //1 = north, 2 = south, 3 = west, 4 = east
        public int speed = 1;

        public void move()
        {
            if (direction == 1)
            {
                frm1.label2.Location = new Point(frm1.label2.Location.Y - speed);
            }

            if (direction == 2)
            {
                frm1.label2.Location = new Point(frm1.label2.Location.Y + speed);
            }

            if (direction == 3)
            {
                frm1.label2.Location = new Point(frm1.label2.Location.X - speed);
            }

            if (direction == 4)
            {
                frm1.label2.Location = new Point(frm1.label2.Location.X + speed);
            }
        }
    }
}

Form1 frm1 = new Form1();是堆栈溢出发生的地方。我确信这不是一种正确的方法,但是当我尝试不这样做时它告诉我'非静态字段需要一个对象引用。'

1 个答案:

答案 0 :(得分:2)

你有一个递归声明。

Form1实例化一个Robot ...实例化一个Form1 ...它绕圈转,直到你最终炸掉堆栈。

您想要做的是将Form1的实例传递给您的Robot。首先,删除Form1 frm1 = new Form1();行。然后,介绍这个字段:

Form1 frm1;

然后,在Robot

中创建一个构造函数
public Robot(Form1 frm) {
    frm1 = frm; // pass the form in
}

然后,在你的Form1类中,通过传入表单实例在构造函数中实例化你的机器人:

Robot robot1;

public Form1()
{
    InitializeComponent();
    label2.Location = new Point(100,100);
    label1.Text = label2.Location.ToString();
    robot1 = new Robot(this); // "this" is the Form1 instance        
}
相关问题