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?
You cannot rely on the name of the method on the implementing class at all - it can be anything. The C# compilers have so far used the convention of prefixing the method name with the fullname of the interface, but that is an internal implementation detail, and also won't be true for e.g. F#. The proper way is by using
InterfaceMapping
if you want aMethodInfo
for the implementation.For example if we have the following structure
And in an F# project
If we just want to call
GetAnswer()
through reflection then it suffices to get theMethodInfo
for the interfaceHowever say that we want to see if the implementation has the AnswerAttribute. Then it won't be enough to just have the
MethodInfo
for the method on the interface. The name of the method would be"LibBar.IFoo.GetAnswer"
if this had been C#, but we want it to work independent of implementation details in the compiler and language used.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 appropriateBindingFlags
), or get the method from the interface type instead.So given the following structure:
...you can do either this:
...or this: