views:

47

answers:

1

Usually, I access a method in reflection like this:

class Foo
{
    public void M () {
        var m = this.GetType ().GetMethod ("M");
        m.Invoke(this, new object[] {}); // notice the pun
    }
}

However, this fails when M is an explicit implementation:

class Foo : SomeBase
{
    void SomeBase.M () {
        var m = this.GetType ().GetMethod ("M");
        m.Invoke(this, new object[] {}); // fails as m is null
    }
}

How do I access an explicitly implemented method using reflection?

+2  A: 

It's because the name of the method is not "M", it will be "YourNamespace.SomeBase.M". So either you will need to specify that name (along with appropriate BindingFlags), or get the method from the interface type instead.

So given the following structure:

namespace SampleApp
{    
    interface IFoo
    {
        void M();
    }

    class Foo : IFoo
    {
        void IFoo.M()
        {
            Console.WriteLine("M");
        }
    }
}

...you can do either this:

Foo obj = new Foo();
obj.GetType()
    .GetMethod("SampleApp.IFoo.M", BindingFlags.Instance | BindingFlags.NonPublic)
    .Invoke(obj, null);            

...or this:

Foo obj = new Foo();
typeof(IFoo)
    .GetMethod("M")
    .Invoke(obj, null);  
Fredrik Mörk