Is it bad practice to write inline event handlers

前端 未结 3 1568
南方客
南方客 2021-02-04 23:17

Is it bad practice to write inline event handlers ?

For me, I prefer use it when I want to use a local variable in the event handler like the following:

I prefer

3条回答
  •  [愿得一人]
    2021-02-04 23:48

    It's absolutely fine - although there are two caveats:

    • If you're modifying a local variable from within a closure, you should make sure you understand what you're doing.
    • You won't be able to unsubscribe from the event

    Typically I only inline really simple event handlers - for anything more involved, I use lambda expressions (or anonymous methods) to subscribe with a call to an method with a more appropriate method:

    // We don't care about the arguments here; SaveDocument shouldn't need parameters
    saveButton.Click += delegate { SaveDocument(); };
    

提交回复
热议问题