Is there anything wrong with using lambda for winforms event?

后端 未结 2 1568
抹茶落季
抹茶落季 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.

    0 讨论(0)
  • 2021-01-20 05:59

    It is fine; the only subtle point is if you need to unsubscribe it; then you need to store the delegate locally too:

    EventHandler handler = (s,a) => ...
    obj.SomeEvent += handler;
    ...
    obj.SomeEvent -= handler;
    

    Note that if I'm not using either parameter (sender/args) I prefer the anon method syntax:

    obj.SomeEvent += delegate {...};
    

    As this doesn't introduce any extra (unnecessary) variables into scope.

    0 讨论(0)
提交回复
热议问题