匹配委托'System.Timers.ElapsedEventHandler'没有重载

时间:2015-07-30 09:33:53

标签: c#

我正在读这篇文章:http://www.c-sharpcorner.com/UploadFile/naresh.avari/develop-and-install-a-windows-service-in-C-Sharp/ 所以玩Windows服务我遇到了一些问题,因为我缺乏知识。在这部分代码中:

 protected override void OnStart(string[] args)
    {
        timer1 = new Timer();
        this.timer1.Interval = 10800; 
        this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
        timer1.Enabled = true;
    }

    private void timer1_Tick()
    {
       //some code here
    }

    protected override void OnStop()
    {
        timer1.Enabled = false;
      //some code here

    }

this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick); 给出:

  

错误1'timer1_Tick'的重载与委托匹配   'System.Timers.ElapsedEventHandler'

我想知道为什么许多人对这个例子没有问题?

1 个答案:

答案 0 :(得分:6)

事件不再是多播委托。并且您的方法签名与委托签名不匹配,在您的情况下是ElapsedEventHandler委托。

您必须更改代码:

 protected override void OnStart(string[] args)
{
    timer1 = new Timer();
    this.timer1.Interval = 10800; 
    this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
    timer1.Enabled = true;
}

private void timer1_Tick(object sender, ElapsedEventArgs elapsedEventArg)
{
   //some code here
}

protected override void OnStop()
{
    timer1.Enabled = false;
  //some code here

}

你也可以代替:

this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);

这样做:

timer.Elapsed += this.timer1_Tick;