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

Kev*_*ger 24 c# reflection interface

public interface IBar {} 
public interface IFoo : IBar {}

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

我怎样才能得到IBar?

BFr*_*ree 52

Type[] types = typeof(IFoo).GetInterfaces();
Run Code Online (Sandbox Code Playgroud)

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

Type type = typeof(IFoo).GetInterface("IBar");
Run Code Online (Sandbox Code Playgroud)

  • @mxmissile然后你[阅读文档](http://msdn.microsoft.com/en-us/library/ayfa0fcd.aspx)并了解`接口IBar <T>的名称(用于`GetInterface) `)是`IBar \`1`. (5认同)
  • 如果`IBar`有通用参数怎么办?这个论点不得而知.`"IBar <>"`不起作用. (2认同)
  • @childno.de 原因是因为 Getinterfaces 不会返回泛型类型定义 - 您必须将它们包含在 ..GetTypes().Where(x =&gt; x.IsGenericType /*&amp;&amp; !x.IsGenericTypeDefinition*/) 中.Select(x =&gt; x.GetGenericTypeDefinition()) (2认同)

Coi*_*oin 27

接口不是基本类型.接口不是继承树的一部分.

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

typeof(IFoo).GetInterfaces()
Run Code Online (Sandbox Code Playgroud)

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

typeof(IFoo).GetInterface("IBar")
Run Code Online (Sandbox Code Playgroud)

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

例:

if(foo is IBar) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

相当于:

if(typeof(IBar).IsAssignableFrom(foo.GetType())) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

if(typeof(IBar).IsAssignableFrom(typeof(IFoo))) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)