【发布时间】:2010-10-07 00:22:47
【问题描述】:
public interface IBar {}
public interface IFoo : IBar {}
typeof(IFoo).BaseType == null
如何获得 IBar?
【问题讨论】:
标签: c# reflection interface
public interface IBar {}
public interface IFoo : IBar {}
typeof(IFoo).BaseType == null
如何获得 IBar?
【问题讨论】:
标签: c# reflection interface
Type[] types = typeof(IFoo).GetInterfaces();
编辑:如果你特别想要 IBar,你可以这样做:
Type type = typeof(IFoo).GetInterface("IBar");
【讨论】:
IBar 有一个通用参数怎么办?并且这个论点是未知的。 "IBar<>" 不起作用。
interface IBar<T> 的名字(对于GetInterface 而言)是IBar`1。
GetType().Assembly.GetTypes().Where(type => type.GetInterface(typeof(IPrefabForXmlInstantiater<>).Name) != null); 有效但 GetType().Assembly.GetTypes().Where(type => type.GetInterfaces().Contains(typeof(IPrefabForXmlInstantiater<>))); 无效;/
nameof 获取Type type = typeof(IFoo).GetInterface(nameof(IBar)); 类型的名称
接口不是基本类型。接口不是继承树的一部分。
要访问接口列表,您可以使用:
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 尝试完全等效。
【讨论】: