如何查找方法是否实现特定接口

我有一个方法的MehtodBase,我需要知道该方法是否是特定接口的实现。 所以,如果我有以下课程:

class MyClass : IMyInterface { public void SomeMethod(); } 

实现界面:

 interface IMyInterface { void SomeMethod(); } 

我希望能够在运行时(使用reflection)发现某个方法是否实现了IMyInterface。

您可以使用GetInterfaceMap

 InterfaceMapping map = typeof(MyClass).GetInterfaceMap(typeof(IMyInterface)); foreach (var method in map.TargetMethods) { Console.WriteLine(method.Name + " implements IMyInterface"); } 

您可以使用Type.GetInterfaceMap()

 bool Implements(MethodInfo method, Type iface) { return method.ReflectedType.GetInterfaceMap(iface).TargetMethods.Contains(method); } 

如果你不必使用reflection,那么不要。 它不像使用is运算符或as运算符as高效

 class MyClass : IMyInterface { public void SomeMethod(); } if ( someInstance is IMyInterface ) dosomething(); var foo = someInstance as IMyInterface; if ( foo != null ) foo.SomeMethod();