lundi 22 mai 2017

Dynamically redefine add and remove methods of events

I have something like that :

public abstract class BaseClass
{
    protected void ToDoOnAdd()
    {

    }

    protected void ToDoOnRemove()
    {

    }
}

public class TopClass : BaseClass
{
    public event EventHandler OnEvent;
}

What I would like to do is to call the method ToDoOnAdd each time OnEvent += ... is called and ToDoOnRemove when OnEvent -= ... is called, and that for each events defined in classes derived from BaseClass.

I know that I can do something like :

public class TopClass : BaseClass
{
    private event EventHandler onEvent;

    public event EventHandler OnEvent
    {
        add
        {
            onEvent += value;
            ToDoOnAdd();
        }
        remove
        {
            onEvent -= value;
            ToDoOnRemove();
        }
    }
}

but I would like to find a solution to do this dynamically so I (or other developpers using BaseClass) don't have to do this for each events.

Is there a way to use reflection in the constructor of BaseClass?

   public BaseClass()
    {
        var events = this.GetType().GetEvents();
        foreach (var ev in events)
        {
            ???
        }
    }

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire