I have a question: if I have a MethodInfo object for a method obtained from an interface type, and I also have a Type object for a class that implements this interface, but it implements the specified method using an explicit implementation, how to correctly get the corresponding object MethodInfo for an implementation method in this class?
The reason I need to do this is because the implementation methods may have some attributes applied to them, and I need to find them through reflection, but the class that needs to find these attributes has only an object reference for the implementation class , and a Type object (+ corresponding MethodInfo objects) for the interface.
So let's say I have the following program:
using System;
using System.Reflection;
namespace ConsoleApplication8
{
public interface ITest
{
void Test();
}
public class Test : ITest
{
void ITest.Test()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
Type interfaceType = typeof(ITest);
Type classType = typeof(Test);
MethodInfo testMethodViaInterface =
interfaceType.GetMethods()[0];
MethodInfo implementingMethod =
classType.GetMethod("Test");
Console.Out.WriteLine("interface: " +
testMethodViaInterface.Name);
if (implementingMethod != null)
Console.Out.WriteLine("class: " +
implementingMethod.Name);
else
Console.Out.WriteLine("class: unable to locate");
Console.Out.Write("Press enter to exit...");
Console.In.ReadLine();
}
}
}
Doing this gives me:
interface: Test
class: unable to locate
Press enter to exit...
The code has a .GetMethod call with ??? a comment. This part is what I need help with. Either what I need to specify here (and I tested a lot, which brings me to another), or what I need to replace this code.
Since I used an explicit method implementation from the interface, the actual method name is not just "Test". If I discard the entire contents of the GetMethods () array of a class type, using this code:
foreach (var mi in classType.GetMethods(
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
Console.Out.WriteLine(mi.Name);
}
then I get the following:
ConsoleApplication8.ITest.Test <-- this is the one I want
ToString
Equals
GetHashCode
GetType
Finalize
MemberwiseClone
it is clear that the name has the full name of the interface and its namespace in front of it. However, because of the overload, what I think I need to do is find all such implementation methods in the class (i.e., provided that there are several testing methods that vary in parameters), and then compare the parameters.
? , , MethodInfo , , , , MethodInfo.
, , , , , , , .
:
foreach (var mi in classType.GetMethods(
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
if (mi.GetBaseDefinition() == testMethodViaInterface)
Console.Out.WriteLine(mi.Name);
}
, , GetBaseDefinition MethodInfo .
?