计时器变量为空,这是为倒计时计时器声明的吗



我有这段代码,它在C#中用于倒计时。我似乎找不到为什么我的变量t为空。我在一个单独的项目中尝试了这个代码,它运行得很好。我试着把它合并到另一个项目中,它说变量t为null。

public partial class tracker : Form
{
System.Timers.Timer t;
int h1, m1, s1;
public tracker()
{
InitializeComponent();
}
private void tracker_Load(object sender, EventArgs e)
{
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEventWork;
}
private void btnLogin_Click(object sender, EventArgs e)
{
t.Start();
btnLogin.Enabled = false;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectedText = DateTime.Now.ToString("MM/dd/yyyyn");
richTextBox2.SelectedText = "Time Inn";
richTextBox3.SelectedText = DateTime.Now.ToString("HH:mm:ssn");
richTextBox4.SelectedText = "n";
richTextBox5.SelectedText = "n";
}
}

您得到的错误t为null,因为t.Start()在实例化Timer对象t之前调用。

要解决这个问题,可以在t.start()之前实例化,也可以在构造函数中创建一个对象。

public tracker()
{
InitializeComponent();
//Here you can instantiate Timer class
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEventWork;
}
private void tracker_Load(object sender, EventArgs e)
{
//Do NOT create object of Timer class here
}
private void btnLogin_Click(object sender, EventArgs e)
{

t.Start();
...
}

最新更新