Unsubscribe anonymous method in C#

前端 未结 11 1365
夕颜
夕颜 2020-11-22 05:16

Is it possible to unsubscribe an anonymous method from an event?

If I subscribe to an event like this:

void MyMethod()
{
    Console.WriteLine(\"I di         


        
11条回答
  •  醉梦人生
    2020-11-22 06:14

    Kind of lame approach:

    public class SomeClass
    {
      private readonly IList _eventList = new List();
    
      ...
    
      public event Action OnDoSomething
      {
        add {
          _eventList.Add(value);
        }
        remove {
          _eventList.Remove(value);
        }
      }
    }
    
    1. Override the event add/remove methods.
    2. Keep a list of those event handlers.
    3. When needed, clear them all and re-add the others.

    This may not work or be the most efficient method, but should get the job done.

提交回复
热议问题