C# event removal syntax

后端 未结 3 1141
名媛妹妹
名媛妹妹 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:48

    The "new MyHandler" is actually redundant. You can simply do

    Something += HandleSomething; // add
    Something -= HandleSomething; // remove
    

    All events in C# are multicast delegates, so the += and -= syntax indicates that you are adding/removing a delegate to the list of delegates that will be called.

    As for what's going on behind the scenes, the best explanation that I've found is Jon Skeet's.

提交回复
热议问题