Is there anything wrong with using lambda for winforms event?

后端 未结 2 1608
抹茶落季
抹茶落季 2021-01-20 05:14

This is a very simple question. I\'m asking because I\'ve never seen it before which makes me wonder if there\'s something wrong.

comboBox1.MouseEnter += (a         


        
2条回答
  •  忘掉有多难
    2021-01-20 05:49

    This is perfectly acceptable, however, since these are anonymous delegates, there is no way to unsubscribe the event handler.

    That is:

    // Subscribe lambda as event handler
    comboBox1.MouseEnter += (a, b) => comboBox1.Focus(); 
    
    // Try to unsubscribe a _different_ lambda with identical syntax. 
    // The first lambda is still subscribed
    comboBox1.MouseEnter -= (a, b) => comboBox1.Focus(); 
    

    Whether that is a problem or not depends on your application and use.

提交回复
热议问题