How to remove all event handlers from an event

后端 未结 18 1603
再見小時候
再見小時候 2020-11-22 01:20

To create a new event handler on a control you can do this

c.Click += new EventHandler(mainFormButton_Click);

or this

c.Cli         


        
18条回答
  •  孤独总比滥情好
    2020-11-22 01:36

    From Removing All Event Handlers:

    Directly no, in large part because you cannot simply set the event to null.

    Indirectly, you could make the actual event private and create a property around it that tracks all of the delegates being added/subtracted to it.

    Take the following:

    List delegates = new List();
    
    private event EventHandler MyRealEvent;
    
    public event EventHandler MyEvent
    {
        add
        {
            MyRealEvent += value;
            delegates.Add(value);
        }
    
        remove
        {
            MyRealEvent -= value;
            delegates.Remove(value);
        }
    }
    
    public void RemoveAllEvents()
    {
        foreach(EventHandler eh in delegates)
        {
            MyRealEvent -= eh;
        }
        delegates.Clear();
    }
    

提交回复
热议问题