我有一个方法的MehtodBase,我需要知道该方法是否是特定接口的实现.所以,如果我有以下课程:
class MyClass : IMyInterface
{
public void SomeMethod();
}
Run Code Online (Sandbox Code Playgroud)
实现界面:
interface IMyInterface
{
void SomeMethod();
}
Run Code Online (Sandbox Code Playgroud)
我希望能够在运行时(使用反射)发现某个方法是否实现了IMyInterface.
The*_*ing 15
你可以用GetInterfaceMap它.
InterfaceMapping map = typeof(MyClass).GetInterfaceMap(typeof(IMyInterface));
foreach (var method in map.TargetMethods)
{
Console.WriteLine(method.Name + " implements IMyInterface");
}
Run Code Online (Sandbox Code Playgroud)
你可以用Type.GetInterfaceMap()它:
bool Implements(MethodInfo method, Type iface)
{
return method.ReflectedType.GetInterfaceMap(iface).TargetMethods.Contains(method);
}
Run Code Online (Sandbox Code Playgroud)