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

后端 未结 4 659
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 18:50

    You can also control subscriptions and unsubsriptions with this declaration. But you also have to iterate through dictionary and call manually subscribed delegates.

        private Dictionary TestEvents { get; }
    
        public event EventHandler TestEvent
        {
            add
            {
                string name = value.GetType().FullName;
                if (!TestEvents.ContainsKey(name))
                {
                    TestEvents.Add(name, value);
                }
            }
            remove
            {
                string name = value.GetType().FullName;
                if (TestEvents.ContainsKey(name))
                {
                    TestEvents.Remove(name);
                }
            }
        }
    

提交回复
热议问题