2011-09-11 60 views
12

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

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

实现接口:

interface IMyInterface 
{ 
    void SomeMethod(); 
} 

我希望能够在运行时发现(使用反射)如果某个方法实现IMyInterface的。

+1

你的意思是要确定是否'MyClass.SomeMethod()'是一个明确的执行'IMyInterface.SomeMethod()'? –

+0

不一定是显式的,但我想知道我得到的方法对象是否是特定接口方法的实现。 –

回答

12

您可以使用GetInterfaceMap这一点。

InterfaceMapping map = typeof(MyClass).GetInterfaceMap(typeof(IMyInterface)); 

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

+1。真的很棒,从来没有听过这个。 – Tigran

+0

不幸的是,它不适用于TypeBuilder。 –

-5

如果你不必使用反射,那么不要。它并不像高性能的端口,比如,用的is运营商或运营商as

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

if (someInstance is IMyInterface) dosomething(); 

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

我想知道,反射提供的方法实现了一个接口 - 不叫它 –

+0

如果你使用is并且它返回true,那么你知道它实现了你的接口。 –

+0

再次 - 我对查询方法库感兴趣,以确定该方法是在接口而不是实例中实现的方法。 –

6

您可以使用该Type.GetInterfaceMap()

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

这很好。值得注意的是,InterfaceMapping是一个结构体,所以你不会检查它为null,而是捕获一个ArgumentException。 – user420667

相关问题