How to ensure an event is only subscribed to once

前端 未结 7 1779
南旧
南旧 2020-11-27 04:20

I would like to ensure that I only subscribe once in a particular class for an event on an instance.

For example I would like to be able to do the following:

7条回答
  •  被撕碎了的回忆
    2020-11-27 04:30

    As others have shown, you can override the add/remove properties of the event. Alternatively, you may want to ditch the event and simply have the class take a delegate as an argument in its constructor (or some other method), and instead of firing the event, call the supplied delegate.

    Events imply that anyone can subscribe to them, whereas a delegate is one method you can pass to the class. Will probably be less surprising to the user of your library then, if you only use events when you actually wnat the one-to-many semantics it usually offers.

提交回复
热议问题