How can I access an explicitly implemented method using reflection?

I usually refer to the method in reflection as follows:

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 to access an explicitly implemented method using reflection?

+4
source share
1 answer

This is because the method name is not "M" , it will be "YourNamespace.SomeBase.M" . Therefore, either you will need to specify this name (along with the corresponding BindingFlags ), or instead get the method from the interface type.

So, the following structure is given:

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

... You can do it:

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

... or that:

 Foo obj = new Foo(); typeof(IFoo) .GetMethod("M") .Invoke(obj, null); 
+8
source

All Articles