C# event removal syntax

后端 未结 3 1143
名媛妹妹
名媛妹妹 2021-01-05 05:31

I am confused by the syntax for removing event handlers in C#.

Something += new MyHandler(HandleSomething); // add
Something -= new MyHandler(HandleSomething         


        
3条回答
  •  太阳男子
    2021-01-05 05:51

    The += and the -= are syntax shortcuts for built-in internal methods named Add(), and Remove(), which add or remove a pointer to an internal linked list of delegates that the delegate has as a private field. When you run Remove, it starts at the head of the linked list and examines each delegate in the list one at a time until it finds one that is "equal" to the one you passed to the Remove() method. ( using -= syntax)

    Then, it removes that one from the linked list, and patches the linked list to retain it's connectivity...

    In this context, the 'equals' method (for a delegate()) is overridden so that it only compares the target of the delegate, and the methodPtr, which will be the same even though you have created a new delegate to pass to Remove...

提交回复
热议问题