I want to be able to use reflection to tell that an implementation of the method GetName
in SomClassImpl
comes from the interface IHasName
. As an example:
public interface IHasName
{
string GetName();
}
public interface IOtherInterface
{
//...elided...
}
public class MyClass : IHasName, IOtherInterface
{
/*
* I want to use reflection to know this
* implements IHasName.GetName()
*/
public string GetName()
{
return "me";
}
}
Is this possible?
When I tried typeof(MyClass).GetMethod("GetName").GetBaseDefinition().DeclaringType
and typeof(MyClass).GetMethod("GetName").DeclaringType
, they both return the implementing class, not the interface.
I see two possibilities your scenario to happen:
In the former case, typeof(Foo).GetMethod("GetName", BindingFlags.Public | BindingFlags.Instance | BindiFoongFlags.DeclaredOnly)
returns the method info.
In the latter case, typeof(Bar).GetMethod("GetName", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
returns null
.
See an example here .
The following will tell if the object implements the interface:
unkObj is IHasName
This will too if using reflection on a type instead of an object:
typeof(IHasName).IsAssignableFrom(typeof(MyClass))
This will get the method associated with the interface, and invoking it with any type that implements the interface with call the associated method in its class:
MethodInfo methodIHasName = typeof(IHasName).GetMethod("GetName", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
string name = methodIHasName.Invoke(unkObj, new object[0]);
If you absolutely need to get the MethodInfo
of MyClass
and all you have is the MethodInfo
of the interface IHasName
, you can map the interface as follows: (Thanks @Alexei Levenkov for the link)
var map = typeof(MyClass).GetInterfaceMap(methodIHasName.DeclaringType);
var index = Array.IndexOf(map.InterfaceMethods, methodIHasName);
return map.TargetMethods[index];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.