I need to be able to determine if a given method or property comes from a particular interface and is explicitly implemented.
Has anyone done this and is it actually possible to get this information by the means of .NET reflection?
Update
As can be seen in comments below the accepted answer, the actual thing I am trying to accomplish is to call the method that implements a particular interface via reflection. Since the possibility to have multiple interfaces with the same method signature, I wanted to determine the right implementation to invoke based on the interface. In my scenario, the implementation type, interface and method name are determined at runtime, so I cannot use simple casting in my case.
Explicitly implemented interface methods in C# are private in the target class. You can use this fact and create this extension method to return only these methods:
static IEnumerable<MethodInfo> GetExplicitlyImplementedMethods(this Type targetType,
Type interfaceType)
{
return targetType.GetInterfaceMap(interfaceType).TargetMethods.Where(m => m.IsPrivate);
}
Note: this is for C# only.
UPDATE: But, from your requirements, it seems that you only want to know which methods implement which interface methods, without really caring about whether the implementation is implicit or explicit. For a solution that works across languages then, this would suffice:
static IEnumerable<MethodInfo> GetImplementedMethods(this Type targetType,
Type interfaceType)
{
return targetType.GetInterfaceMap(interfaceType).TargetMethods;
}