Is it safe to add delegates to events with keyword new?

后端 未结 4 444
时光取名叫无心
时光取名叫无心 2021-01-12 20:02

One thing I am concerned with is that I discovered two ways of registering delegates to events.

  1. OnStuff += this.Handle;
  2. OnStuff += new StuffEventHand
相关标签:
4条回答
  • 2021-01-12 20:54

    If I remember correctly, the first alternative is merely syntactic sugar for the second.

    0 讨论(0)
  • 2021-01-12 20:56

    Number one is just shorthand that will generate the same MSIL as the 2nd one, at compile type it'll look at this.Handle and infer the delegate to instantiate. But you should never unsubscribe by using new.

    So there is no difference between the 2, just some syntactic sugar to make our code cleaner.

    0 讨论(0)
  • 2021-01-12 21:02

    You don't need to worry about keeping a reference to the originally registered delegate, and you will not start a "nasty memory pool".

    When you call "OnStuff -= new StuffEventHandler(this.Handle);" the removal code does not compare the delegate you are removing by reference: it checks for equality by comparing references to the target method(s) that the delegate will call, and removes the matching delegates from "OnStuff".

    By the way, "OnStuff" itself is a delegate object (the event keyword that I assume you have in your declaration simply restricts the accessibility of the delegate).

    0 讨论(0)
  • 2021-01-12 21:02

    I was under the impression that 2 is just syntax sugar. They should be exactly the same thing.

    0 讨论(0)
提交回复
热议问题