Can I tie an anonymous function to a Timer's t

2019-03-25 09:00发布

问题:

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? That's the thought that went through my head when I thought of this.

Is it possible to tie an anonymous function to a Timer's tick event? Here's what I'm trying to do.

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

回答1:

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!");
};


回答2:

A complete example would be:

    Timer timer = new Timer();
    timer.Interval = 500;
    timer.Tick += (t, args) =>
        {
            timer.Enabled = false;
            /* some code */
        };
    timer.Enabled = true;


回答3:

You use the delegate keyword for anonymous methods:

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

In C# 3.0 and later, you can also use lambdas:

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


标签: c# timer