如何找出一个方法是否实现了特定的接口

17
我有一个方法的MethodBase,需要知道该方法是否是特定接口的实现。假设我有以下类:
class MyClass : IMyInterface
{
    public void SomeMethod();
}

实现接口:

interface IMyInterface
{
    void SomeMethod();
}

我想在运行时(使用反射)确定某个方法是否实现了IMyInterface。


1
你的意思是要确定 MyClass.SomeMethod() 是否为 IMyInterface.SomeMethod() 的显式实现吗? - Frédéric Hamidi
我想知道我得到的 MethodBase 对象是否是特定接口方法的实现。 - Dror Helper
3个回答

16
你可以使用GetInterfaceMap来实现这个目的。
InterfaceMapping map = typeof(MyClass).GetInterfaceMap(typeof(IMyInterface));

foreach (var method in map.TargetMethods)
{
    Console.WriteLine(method.Name + " implements IMyInterface");
}

11
你可以使用Type.GetInterfaceMap()来实现这个功能:
bool Implements(MethodInfo method, Type iface)
{
    return method.ReflectedType.GetInterfaceMap(iface).TargetMethods.Contains(method);
}

这很好。需要注意的是,InterfaceMapping是一个结构体,因此您不需要检查它是否为null,而是要捕获ArgumentException异常。 - user420667

-7
如果你不必使用反射,那就不要用。它的性能不如使用例如is操作符或者as操作符。
class MyClass : IMyInterface
{
    public void SomeMethod();
}

if ( someInstance is IMyInterface ) dosomething();

var foo = someInstance as IMyInterface;
if ( foo != null ) foo.SomeMethod();

我想知道通过反射提供的方法是否实现了一个接口 - 而不是调用它。 - Dror Helper
如果你使用 is 并且返回 true,那么你就知道它实现了你的接口。 - Muad'Dib
我对查询MethodBase感兴趣,以确定该方法是否是接口中方法的实现而不是实例。 - Dror Helper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接