Adding and Removing Anonymous Event Handler

后端 未结 6 1954
野性不改
野性不改 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 02:43

    That won't work I'm afraid, since the two lambda expressions (and delegates) that you declared are actually different objects, and return different references. Hence, the removal of the handler (-=) will always fail.

    The common solution to this problem (where you need to remove the handler) is simply to refactor the lamba expression into a proper method. An alternative is to maintain a class variable for the event handler delegate, and add and remove this, though I am personally not a fan of it. (It's more hassle than just creating a normal method, if anything.)

提交回复
热议问题