Preventing same Event handler assignment multiple times

前端 未结 4 1225
一向
一向 2020-12-13 23:37

If I am assigning an event handler at runtime and it is in a spot that can be called multiple times, what is the recommended practice to prevent multiple assignments of the

4条回答
  •  时光取名叫无心
    2020-12-14 00:17

    Baget is right about using an explicitly implemented event (although there's a mixture there of explicit interface implementation and the full event syntax). You can probably get away with this:

    private EventHandler foo;
    
    public event EventHandler Foo
    {
        add
        {
            // First try to remove the handler, then re-add it
            foo -= value;
            foo += value;
        }
        remove
        {
            foo -= value;
        }
    }
    

    That may have some odd edge cases if you ever add or remove multicast delegates, but that's unlikely. It also needs careful documentation as it's not the way that events normally work.

提交回复
热议问题