vendredi 8 mai 2015

Get all concrete implementations of a delegate collection in C# via reflection

Yeah, I tried to make the title smaller, but I couldn't.

I'm very new to reflection, so I'm struggling with a problem that I don't know if it's even possible to solve.

I'll use some simple delegate example to describe it.

public void Main() {
    var manager = new EvManager();
    var class1 = new Class1(manager);
    var class2 = new Class2(manager);

    manager.ExecuteIt(5, 12);
    /*
    This outputs:
    In Class1 -> 17
    In Class2 -> 18
    */
}

public class EvManager {
    public delegate void SumDelegate(int a, int b);
    private SumDelegate sum;

    public void AddDelegate(SumDelegate s) {
        sum += s;
    }

    public void ExecuteIt(int a, int b) {
        sum.Invoke(a, b);
    }
}

public class Class1 {
    public Class1(EvManager m) {
        m.AddDelegate(MySum);
    }

    private void MySum(int a, int b) {
        Console.Write("In Class1 -> " + (a + b));
    }
}

public class Class2 {
    public Class2(EvManager m) {
        m.AddDelegate(MyOtherSum);
    }

    private void MyOtherSum(int a, int b){
        Console.Write("In Classe2 -> " + (a + b));
    }
}

Okay, that's the example. What do I want from it? I want, through the EvManager "sum" delegate property be able to access the concrete implementations of all the methods that it invokes.

This is basically what I want:

class EvManager {
    private SumDelegate sum;
    public void ExecuteIt(int a, int b) {
        var invocationList = sum.GetInvocationList();
        foreach (var m in invocationList) {
            // m is a reference to the annonymous call.
            // Through reflection, I want to access the concrete method name.
            // In this case, the first iteration "MySum", and the second "MyOtherSum"
            // Is this possible?

            // Like...
            // var concreteMethodName = m.GetMethod().ConcreteCallerType.GetMethod(m.GetConreteMethodName());
            // Or something like that?
        }   
    }
}

Hope I made my problem clear, this is killing me.





Aucun commentaire:

Enregistrer un commentaire