Adding and Removing Anonymous Event Handler

后端 未结 6 1959
野性不改
野性不改 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:52

    If you need to unsubscribe an event handler, you'll need to have a definite reference to a concrete delegate. Looking at Delegate.Equality you will find that delegates aren't just compared using reference equality, however this doesn't matter for anonymous delegates.

    For an anonymous delegate, the compiler (basically) just creates a new "non-anonymous" delegate for each anonymous delegate, even if the delegate bodies are the same. Because of this, the framework will not find the delegate to unsubscribe when you use the code example you gave.

提交回复
热议问题