【问题标题】:How to find if a method is implementing specific interface如何查找方法是否正在实现特定接口
【发布时间】:2011-09-11 15:32:37
【问题描述】:

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

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

实现接口:

interface IMyInterface
{
    void SomeMethod();
}

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

【问题讨论】:

  • 您的意思是要确定MyClass.SomeMethod() 是否是IMyInterface.SomeMethod() 的显式实现?
  • 不一定是明确的,但我想知道我得到的方法库对象是否是特定接口方法的实现。

标签: c# reflection


【解决方案1】:

您可以为此使用Type.GetInterfaceMap()

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

【讨论】:

  • 这很好。值得注意的是,InterfaceMapping 是一个结构,因此您无需检查它是否为 null,而是捕获 ArgumentException。
【解决方案2】:

您可以为此使用GetInterfaceMap

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

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

【讨论】:

    【解决方案3】:

    如果您不必使用反射,那么就不要。它不如使用 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,那么你就知道它实现了你的接口。
    • 再次 - 我有兴趣查询方法库,以确定该方法是接口而不是实例中方法的实现。
    猜你喜欢
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    相关资源
    最近更新 更多