I have a MethodInfo
object that represents an explicitly-implemented interface method, as follows.
MethodInfo GetMethod()
{
return typeof(List<>).GetMethod(
"System.Collections.IEnumerable.GetEnumerator",
BindingFlags.Instance | BindingFlags.NonPublic);
}
How do I query this MethodInfo
object to obtain the interface type it implements, a Type
object representing System.Collections.IEnumerable
? The InterfaceMapping
structure provides the inverse operation, getting the MethodInfo
object of a type that implements a given interface, so that won't work.
Note that this is a contrived example as I can clearly parse the method name for this information. I'd like to avoid doing this if possible.
I don't know of a direct way of doing this, but you can obviously use InterfaceMapping in reverse: iterate over all interfaces implemented by the method's declaring type, checking if the method is in the interface map for that interface:
foreach (Type itf in method.DeclaringType.GetInterfaces())
{
if (method.DeclaringType.GetInterfaceMap(itf).TargetMethods.Any(m => m == method))
{
Console.WriteLine("match: " + itf.Name);
}
}
Although this may seem a bit inefficient, most types implement few enough interfaces that it shouldn't be a big deal. Appreciate it's not terribly elegant though!