C#接口inheritance

鉴于:

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 

以下是获取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(); 

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

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

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

考虑IA是IB的接口,而不是它的基础。

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

尝试

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