Adding and Removing Anonymous Event Handler

后端 未结 6 1953
野性不改
野性不改 2020-11-29 02:14

I was wondering if this actually worked ?

private void RegisterKeyChanged(T item) 
{
    item.OnKeyChanged += (o, k) => ChangeItemKey((T)o, k);
}

private         


        
6条回答
  •  無奈伤痛
    2020-11-29 03:00

    There's an MSDN page that talks about this:

    How to Subscribe to and Unsubscribe from Events

    Note in particular:

    If you will not have to unsubscribe to [sic] an event later, you can use the addition assignment operator (+=) to attach an anonymous method to the event.

    And also:

    It is important to notice that you cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, it is necessary to go back to the code where you subscribe to the event, store the anonymous method in a delegate variable, and then add the delegate to the event . In general, we recommend that you do not use anonymous functions to subscribe to events if you will have to unsubscribe from the event at some later point in your code.

提交回复
热议问题