Can I tie an anonymous function to a Timer's tick event?

前端 未结 3 1962
渐次进展
渐次进展 2021-02-07 16:09

If a Tick-handling function will only be used in one context (i.e. always in the same function in combination with the same Timer object), why bother make it a separate function

3条回答
  •  逝去的感伤
    2021-02-07 16:35

    You're looking for Anonymous Methods:

    myTimer.Tick += delegate (object sender, EventArgs e) {
        MessageBox.Show("Hello world!");
    };
    

    You can also omit the parameters:

    myTimer.Tick += delegate {
        MessageBox.Show("Hello world!");
    };
    

    In C# 3.0, you can also use a Lambda Expression:

    myTimer.Tick += (sender, e) => {
        MessageBox.Show("Hello world!");
    };
    

提交回复
热议问题