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)
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)