如何通过reflection获取接口基类型?

public interface IBar {} public interface IFoo : IBar {} typeof(IFoo).BaseType == null 

我怎样才能得到IBar?

 Type[] types = typeof(IFoo).GetInterfaces(); 

编辑:如果您特别想要IBar,您可以:

 Type type = typeof(IFoo).GetInterface("IBar"); 

接口不是基本类型。 接口不是inheritance树的一部分。

要访问interfaces列表,您可以使用:

 typeof(IFoo).GetInterfaces() 

或者如果您知道接口名称:

 typeof(IFoo).GetInterface("IBar") 

如果您只想知道某个类型是否与其他类型(我怀疑您正在寻找)隐式兼容,请使用type.IsAssignableFrom(fromType)。 这相当于’is’关键字,但与运行时类型相同。

例:

 if(foo is IBar) { // ... } 

相当于:

 if(typeof(IBar).IsAssignableFrom(foo.GetType())) { // ... } 

但在你的情况下,你可能更感兴趣:

 if(typeof(IBar).IsAssignableFrom(typeof(IFoo))) { // ... } 

除了其他海报写的内容之外,您还可以从GetInterface()列表中获取第一个接口(如果列表不为空)以获取IFoo的直接父级。 这将完全等同于.BaseType尝试。