What's a proper way to unsibscribe from events in c#?

后端 未结 4 677
Happy的楠姐
Happy的楠姐 2021-01-13 18:09

I have a model class with an event which I subscribe from other classes. I want to subscribe and un-subscribe in each class correctly.

  • First I want to guarant
4条回答
  •  梦谈多话
    2021-01-13 19:10

    If you want to guarantee you only unsubscribe once, you can use the GetInvocationList method:

    if (_model.OnMyEvent != null && _model.GetInvocationList().Contains(EventHandle))
    {
        _model.OnMyEvent -= EventHandle
    }
    

    But as mentioned by the others, you can unsubscribe multiple times. If this really isn't a problem, keep it that way. The solution I propose is just code-noise. Simply unsubscribing in one line is much neater, and easier to read when your class starts to grow.

提交回复
热议问题