我有一个方法的MehtodBase,我需要知道该方法是否是特定接口的实现。 所以,如果我有以下类:如何找到一种方法是否实现特定接口
class MyClass : IMyInterface
{
public void SomeMethod();
}
实现接口:
interface IMyInterface
{
void SomeMethod();
}
我希望能够在运行时发现(使用反射)如果某个方法实现IMyInterface的。
我有一个方法的MehtodBase,我需要知道该方法是否是特定接口的实现。 所以,如果我有以下类:如何找到一种方法是否实现特定接口
class MyClass : IMyInterface
{
public void SomeMethod();
}
实现接口:
interface IMyInterface
{
void SomeMethod();
}
我希望能够在运行时发现(使用反射)如果某个方法实现IMyInterface的。
您可以使用GetInterfaceMap
这一点。
InterfaceMapping map = typeof(MyClass).GetInterfaceMap(typeof(IMyInterface));
foreach (var method in map.TargetMethods)
{
Console.WriteLine(method.Name + " implements IMyInterface");
}
+1。真的很棒,从来没有听过这个。 – Tigran
不幸的是,它不适用于TypeBuilder。 –
如果你不必使用反射,那么不要。它并不像高性能的端口,比如,用的is
运营商或运营商as
class MyClass : IMyInterface
{
public void SomeMethod();
}
if (someInstance is IMyInterface) dosomething();
var foo = someInstance as IMyInterface;
if (foo != null) foo.SomeMethod();
我想知道,反射提供的方法实现了一个接口 - 不叫它 –
如果你使用is并且它返回true,那么你知道它实现了你的接口。 –
再次 - 我对查询方法库感兴趣,以确定该方法是在接口而不是实例中实现的方法。 –
您可以使用该Type.GetInterfaceMap()
:
bool Implements(MethodInfo method, Type iface)
{
return method.ReflectedType.GetInterfaceMap(iface).TargetMethods.Contains(method);
}
这很好。值得注意的是,InterfaceMapping是一个结构体,所以你不会检查它为null,而是捕获一个ArgumentException。 – user420667
你的意思是要确定是否'MyClass.SomeMethod()'是一个明确的执行'IMyInterface.SomeMethod()'? –
不一定是显式的,但我想知道我得到的方法对象是否是特定接口方法的实现。 –