【问题标题】:Getting list of interface methods available in derived interface获取派生接口中可用的接口方法列表
【发布时间】:2017-05-12 17:43:36
【问题描述】:

我有一个 A 类:

public class A: ParentA, IA
{
    public void func()
    {
    }
    public void ConsumableMethod()
    {
    }
    public void MethodA()
    {
    }
    public void ConsumableMethodFromIB()
    {
    }
}

public interface IA : IB
{
    void ConsumableMethod();
}

public interface IB
{
    void ConsumableMethodFromIB();
}

public abstract class ParentA
{
    public abstract void MethodA();

    public void MethodB()
    {
    }
}

我想要接口 IA 中可用的方法列表。为此我正在做这样的事情:

var methods = typeof(IA).GetMethods(BindingFlags.Instance | BindingFlags.Static | 
                BindingFlags.Public | BindingFlags.NonPublic);

通过在 A 上调用 GetMethods,我得到了仅在 A 中声明的方法列表(即 func),在父抽象类中实现的方法(即 MethodB)并实现了接口方法(即ConsumableMethod & ConsumableMethodFromIB)。

我想要的是IA 中可用的方法(包括来自 IB 的方法)。我目前仅通过在 IA 上调用 GetMethods 获得“ConsumableMethod”。我怎样才能得到'ConsumableMethodFromIB'?

【问题讨论】:

  • 抱歉,我无法理解您到底得到/没有得到什么。您能否更新您的问题,说出IA 是什么,methods 返回什么以及您希望它返回什么?另外,您在说什么父抽象类?你的问题中没有。而且,接口不能实现另一个接口。它可以扩展它,但不能实现
  • 你不能得到未实现的方法,因为在这些类中没有关于它们的元信息。

标签: c# .net


【解决方案1】:

正如您已经注意到的,GetMethods 不会返回“父”接口的方法。 GetMethods 可能会返回继承的方法(除非您使用 BindingFlags.DeclaredOnly 标志) - 这就是为什么当您在类型 A 上调用 GetMethods 时看到所有这些方法的原因,它们要么属于此类,要么继承自父类.

如果你想获得“父”接口的方法,你必须手动探索它们,像这样:

static IEnumerable<MethodInfo> GetMethods(Type type) {
    foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Static |
                                               BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
        yield return method;
    }
    if (type.IsInterface) {
        foreach (var iface in type.GetInterfaces()) {
            foreach (var method in GetMethods(iface)) {
                yield return method;
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    您可以使用这组方法/属性找到您要查找的内容:

    • typeof(A).GetInterfaces()
    • typeof(A).GetInterfaceMap(...)
    • MethodInfo.DeclaringType

    并做出区分。

    【讨论】:

      猜你喜欢
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多