【问题标题】:How do I access my control from another method如何从其他方法访问我的控件
【发布时间】:2013-04-16 23:56:21
【问题描述】:

我正在制造太空侵略者,我希望我的子弹从我的大炮所在的位置射出。当我按空格键时,子弹会发射,但我每次按空格键时都需要它能够访问我的 cannonX 的位置,它不允许我访问它的信息。

    public void tsbtnStart_Click(object sender, EventArgs e)
    {

        // Make invader

            Invader invaderX = new Invader();
            pnlBattleField.Controls.Add(invaderX);

        // Mke UFO

            Ufo ufoX = new Ufo();
            pnlBattleField.Controls.Add(ufoX);


        // Make cannon
            Cannon cannonX = new Cannon(this.pnlBattleField.Height - 80);

        if (made == false)
        {
            pnlBattleField.Controls.Add(cannonX);
            made = true;

        }
        Point location = cannonX.PointToScreen(Point.Empty);


        tmrClock.Interval = 200;
        tmrClock.Start();
        tmrClock2.Interval = 100;
        tmrClock2.Start();
    }

    public void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (e.KeyChar == (char)Keys.Space)
        {

            Bullet bulletX = new Bullet(this.pnlBattleField.Height - 80, location.x );
            // "location does not exist in current context

            pnlBattleField.Controls.Add(bulletX);
        }

    }

【问题讨论】:

  • 您需要获取对表单上Cannon 对象的引用,该对象当前位于pnlBattleField.Controls 中的某个位置。
  • 需要引用对象;所以你可以访问。您还必须传递 X 和 Y 轴上的坐标值。
  • 如何引用对象?

标签: c# class variables object scope


【解决方案1】:

locationcannonXtsbtnStart_Click 中的局部变量,因此一旦tsbtnStart_Click 返回,它们就不再存在。使它们成为您的类的属性,以便它们将持续存在并可以在 Form1_KeyPress 和其他方法中访问。

【讨论】:

  • 您好,感谢您的帮助。你能帮我把它们变成我班级的属性吗?我想我必须将它们添加到我的 Cannon 课程中?我做了这样的事情: public int location { get { return location; } } 我迷路了,请帮忙
  • 就像@Sebastien 发布的那样,您可以在课程本身中添加类似:private Point location; 的内容。你可以把它放在你的方法之前或之后。然后你可以在这两种方法中访问相同的location
【解决方案2】:

好吧,你声明

Point location = cannonX.PointToScreen(Point.Empty);

在你的方法中:

public void tsbtnStart_Click(object sender, EventArgs e)

您需要在开始时在类成员中声明此位置。 之后,您将用正确的值覆盖他的值。

像这样:

private Point location = new Point();
location = cannonX.PointToScreen(Point.Empty); // in your method

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多