代码之家  ›  专栏  ›  技术社区  ›  ppiotrowicz

接口继承

  •  16
  • ppiotrowicz  · 技术社区  · 14 年前

    鉴于:

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

    为什么?

    typeof(IB).GetMethods().Count() == 0;
    

    ?

    只是为了清楚:

    public class A
    {
        public void TestMethod()
        {
        }
    }
    
    public class B : A
    {
    }
    
    typeof(B).GetMethods().Count();
    

    是否有效(返回5);

    作为奖励:

    typeof(IB).BaseType == null
    
    4 回复  |  直到 13 年前
        1
  •  11
  •   Manfred    14 年前

    下面是获取IA和IB计数的代码:

    var ibCount = typeof(IB).GetMethods().Count(); // returns 0
    var iaCount = typeof (IB).GetInterfaces()[0].GetMethods().Count(); // return 1
    

    注意,在生产代码中,我不会使用 GetInterfaces()[0] 在我将要使用这个的代码中,我不能假定我总是至少有一个接口。

    我还尝试了如下绑定标志:

    const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
    var ibCount = typeof(IB).GetMethods(bindingFlags).Count();
    

    但是,这仍然会返回0作为接口 IB 仍然不实现方法 TestMethod() . 界面 IA 做。如果同时使用绑定标志 IA IB 是班级。但是,在这种情况下,返回值为5。不要忘记IA隐式地从类派生 Object !

        2
  •  9
  •   Matthew Abbott    14 年前

    这似乎是getmethods函数的设计。它不支持接口中继承的成员。如果要发现所有方法,则需要直接查询每个接口类型。

    查看的社区内容部分 this MSDN article .

        3
  •  2
  •   Tormod    14 年前

    把IA看作是ib的接口,而不是它的基础。

        4
  •  -1
  •   Kristof DB    13 年前

    您必须在getMethods()中定义一些bindingFlags。

    尝试

    typeof(IB).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Count();