samedi 2 mai 2015

Invoke multiple generic interface methods on a class through reflection

I have a generic interface and a class that implements the interface 'n' number of times:

interface IA<T>
{
    T Foo();
}

class Baz1 { }
class Baz2 { }

class Bar : IA<Baz1>, IA<Baz2>
{
    Baz1 Foo() { return new Baz1(); }
    Baz2 Foo() { return new Baz2(); }
}

How can I use reflection to call both Foo methods on an instance of Bar?

I already have the following code to get the interface definitions and the generic type parameters:

class Frobber
{
    void Frob(object frobbee)
    {
        var interfaces = frobbee.GetType()
            .GetInterfaces()
            .Where(i => i.IsGenericType &&
                i.GetGenericTypeDefinition() == typeof(IA<>).GetGenericTypeDefinition());
    }
}





Aucun commentaire:

Enregistrer un commentaire