【问题标题】:How to get interface basetype via reflection?如何通过反射获取接口基类型?
【发布时间】:2010-10-07 00:22:47
【问题描述】:
public interface IBar {} 
public interface IFoo : IBar {}

typeof(IFoo).BaseType == null

如何获得 IBar?

【问题讨论】:

    标签: c# reflection interface


    【解决方案1】:
    Type[] types = typeof(IFoo).GetInterfaces();
    

    编辑:如果你特别想要 IBar,你可以这样做:

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

    【讨论】:

    • 如果IBar 有一个通用参数怎么办?并且这个论点是未知的。 "IBar<>" 不起作用。
    • @mxmissile 然后你read the documentation 并得知interface IBar<T> 的名字(对于GetInterface 而言)是IBar`1
    • @ta.speot.is 这并没有向我解释为什么 GetType().Assembly.GetTypes().Where(type => type.GetInterface(typeof(IPrefabForXmlInstantiater<>).Name) != null); 有效但 GetType().Assembly.GetTypes().Where(type => type.GetInterfaces().Contains(typeof(IPrefabForXmlInstantiater<>))); 无效;/
    • @childno.de 原因是因为 Getinterfaces 不会返回泛型类型定义 - 您必须将它们包含在 ..GetTypes().Where(x => x.IsGenericType /* && !x.IsGenericTypeDefinition*/).Select(x => x.GetGenericTypeDefinition())
    • 只想添加。您可以使用nameof 获取Type type = typeof(IFoo).GetInterface(nameof(IBar)); 类型的名称
    【解决方案2】:

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

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

    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))) {
        // ...
    }
    

    【讨论】:

      【解决方案3】:

      除了其他发帖人写的,你可以从GetInterface() 列表中获取第一个接口(如果列表不为空)来获取IFoo 的直接父级。这将与您的 .BaseType 尝试完全等效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-07
        • 2013-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多