共用方式為


Attaching an Event Handler

Whenever I need to attach an event handler, usually I use one of these methods, a delegate, anonymous method, or lambda expression.

For complex events (more than 3 lines of code), I create a separate method. If the method is short, I use anonymous method. But if the event is just one line, I use lambda expression.

 private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("Hello World!");
}

private void Form1_Load(object sender, EventArgs e)
{
    //This is good for complex events.
    button1.Click += button1_Click;
    //Anonymous method, suitable for short event.
    button2.Click += delegate(object obj, EventArgs arg)
    {
        MessageBox.Show("Hello World!");
    };
    //Lambda expression, great for one line event.
    button3.Click += ((x, y) => MessageBox.Show("Hello World!"));
}