如何通过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尝试。
- initializeCulture of pages在masterPage中的下拉列表的selectedIndexChange之前触发
- EntityFramework.dll中出现“System.InvalidOperationException”类型的exception,但未在用户代码中处理
- 在WPF中,如果窗口离开屏幕,如何将窗口移动到屏幕上?
- 如何使用C#以编程方式安装证书
- 从WAV文件解码DTMF
- 如何设置Accept和Accept-Language标题字段?
- C#Stringbuilder OutOfMemoryException
- 在Switch语句中使用.StartsWith?
- 如何在xml和xslt之间进行转换处理时产生exception错误