C#接口继承

ppi*_*icz 16 c# reflection inheritance interface

鉴于:

public interface IA
{
    void TestMethod();
}

public interface IB : IA
{
}
Run Code Online (Sandbox Code Playgroud)

为什么:

typeof(IB).GetMethods().Count() == 0;
Run Code Online (Sandbox Code Playgroud)

只是要清楚:

public class A
{
    public void TestMethod()
    {
    }
}

public class B : A
{
}

typeof(B).GetMethods().Count();
Run Code Online (Sandbox Code Playgroud)

确实有效(它返回5);

作为奖励:

typeof(IB).BaseType == null
Run Code Online (Sandbox Code Playgroud)

Man*_*red 11

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

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

请注意,在生产代码中我不会GetInterfaces()[0]像在我将使用它的代码中那样使用我不能假设我将始终至少有一个接口.

我也尝试了如下的绑定标志:

const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
var ibCount = typeof(IB).GetMethods(bindingFlags).Count();
Run Code Online (Sandbox Code Playgroud)

但是,由于接口IB仍未实现方法,因此仍将返回0 TestMethod().接口呢IA.如果同时使用绑定标志将工作IAIB为类.但是,在这种情况下,返回值为5.不要忘记IA隐式派生于类Object!


Mat*_*ott 9

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

查看此MSDN文章的社区内容部分.


小智 -1

您必须在 GetMethods() 中定义一些 Bindingflags。

尝试

typeof(IB).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Count();
Run Code Online (Sandbox Code Playgroud)

  • 我忽略了 BindingFlags,因为它们没有帮助;)。 (3认同)