C# Lambda expressions: Why should I use them?

后端 未结 15 1174
栀梦
栀梦 2020-11-22 03:51

I have quickly read over the Microsoft Lambda Expression documentation.

This kind of example has helped me to understand better, though:

delegate in         


        
15条回答
  •  情深已故
    2020-11-22 04:08

    I found them useful in a situation when I wanted to declare a handler for some control's event, using another control. To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.

    private ComboBox combo;
    private Label label;
    
    public CreateControls()
    {
        combo = new ComboBox();
        label = new Label();
        //some initializing code
        combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
    }
    
    void combo_SelectedIndexChanged(object sender, EventArgs e)
    {
        label.Text = combo.SelectedValue;
    }
    

    thanks to lambda expressions you can use it like this:

    public CreateControls()
    {
        ComboBox combo = new ComboBox();
        Label label = new Label();
        //some initializing code
        combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
    }
    

    Much easier.

提交回复
热议问题