在类中调用Form1组件(标签)

时间:2013-10-23 13:09:46

标签: c# forms class label call

美好的一天。我有一个Form1和两个类的程序。当我想在其中一个类中使用label1时它会显示错误当前上下文中不存在名称label1。如何在类中使用label1来显示文本?

namespace snake_game
{

   public class had
   {

       private Rectangle[] snakeRec;
       private SolidBrush brush;
       private int x, y, width, height;
       public Rectangle[] SnakeRec

       {
           get { return snakeRec; }

       }

       public had()
       {
           snakeRec = new Rectangle[3];
           brush = new SolidBrush(Color.Black);


           x = 20;
           y = 0;
           width = 10;
           height = 10;
           for (int i = 0; i < snakeRec.Length; i++)
           {
               snakeRec[i] = new Rectangle(x, y, width, height);
               x -= 10;
           }
}

      ...................................................

............................................... ...............................

       public void drawSnake()
       {
           for (int i = snakeRec.Length - 1; i > 0; i--)
           {
               snakeRec[i] = snakeRec[i - 1];


               for (int j = 1; j < snakeRec.Length; j++)

                   if (snakeRec[i].X == snakeRec[j].X && snakeRec[i].Y == snakeRec[j].Y)
                   {
                       label1.Text = "------";    //here is problem//
                   }
           }
       }

1 个答案:

答案 0 :(得分:0)

你不能,因为你不想那样做 你有一个类had,它是一个Model类。您不希望模型调用您的视图(标签)。

您希望使用MVC模式构建软件,因为它很好。这是Controller(后面的Form1代码),它将调用您的模型(had)来更新视图的标签(Form1)。

例如:

public class had
{
    public void moveDown()
    {
       snakeRec[0].Y += 10; 
    }     
}

public class Form1 : Form
{
    private had _model;

    public void moveDown()
    {
       _model.MoveDown();
       this.drawSnake();
    }     
    public void drawSnake()
    {
        for (int i = this._model.snakeRec.Length - 1; i > 0; i--)
        {
            ....
            label1.Text = "------"; 
            ....
        }
   }
}