为倒数计时器声明的计时器变量为空?

Timer variable is null which is declared for countdown timer?

我有这段代码在 C# 中用于倒计时。我似乎无法找到为什么我的变量 t 为空。我在一个单独的项目上尝试了这段代码,它运行良好。我试图将它合并到另一个项目中,它说变量 t 为空。

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/yyyy\n");
        richTextBox2.SelectedText = "Time In\n";
        richTextBox3.SelectedText = DateTime.Now.ToString("HH:mm:ss\n");
        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();
   ...
}