为什么静态会在尝试更新文本框文本时使其出错

时间:2012-04-12 11:54:08

标签: c# winforms

我有以下代码。 它是一个带有单个文本框的表单。 如果我让myTimer_Tick不是静态的那么它运作正常 - 为什么?

namespace Ariport_Parking
{
  public partial class AirportParking : Form
  {

    //instance variables of the form
    static Timer myTimer;


    public AirportParking()
    {
        InitializeComponent();
        keepingTime(5000);
        txtMessage.Text = "hello";
    }

    //method for keeping time
    public void keepingTime(int howlong) {

        myTimer = new Timer();
        myTimer.Enabled = true;
        myTimer.Tick += new EventHandler(myTimer_Tick);
        myTimer.Interval = howlong;

        myTimer.Start();

    }

    static void myTimer_Tick(Object myObject,EventArgs myEventArgs){
        myTimer.Stop();
        txtMessage.Text = "hello world";
    }

  }

}

2 个答案:

答案 0 :(得分:5)

我认为错误是它无法访问txtMessage。 txtMessage是在表单上声明的实例变量,静态方法无法访问表单的实例数据。 你可以谷歌知道原因。

答案 1 :(得分:1)

因为txtMessage不是静态的,所以需要该类的实例才能被访问。您不需要将myTimer_Tick和计时器设置为静态。或者为了好用lambda而不是myTimer_Tick。

而不是:

myTimer.Tick += new EventHandler(myTimer_Tick);

使用

myTimer.Tick += (sender, e) => { 
    myTimer.Stop();
    txtMessage.Text = "hello world";
};