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

后端 未结 4 448
时光取名叫无心
时光取名叫无心 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 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).

提交回复
热议问题