代码之家  ›  专栏  ›  技术社区  ›  Ryall

在列表中查找IEnumerable<t>时,GetGenerictypedefinition返回false

  •  4
  • Ryall  · 技术社区  · 16 年前

    跟随 this question 为什么 enumerable 在这方面:

    Type type = typeof(List<string>);
    bool enumerable = (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>));
    

    返回 false ?


    编辑1

    由于上述方法不起作用,那么确定类是否实现IEnumerable的最佳方法是什么?

    4 回复  |  直到 16 年前
        1
  •  8
  •   Marc Gravell    16 年前

    在这里,我可以用 GetListType(type) 并检查 null :

    static Type GetListType(Type type) {
        foreach (Type intType in type.GetInterfaces()) {
            if (intType.IsGenericType
                && intType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {
                return intType.GetGenericArguments()[0];
            }
        }
        return null;
    }
    
        2
  •  4
  •   Richard    16 年前

    因为

    (typeof(List<String>)).GetGenericTypeDefinition()
    

    正在返回

    typeof(List<>)
    

    GetGenericTypeDefinition 只能返回一个类型,而不能返回目标实例实现的所有未绑定类型 Type .

    确定是否 X<T> 器具 IY<T> 任何一个

    • 重新定义t(即使其成为真正的类型),并检查具体类型。也就是说 X<string> 实施 IY<string> . 这可以通过反射或 as 操作员。

    • Type.GetInterafces() (或) Type.GetInterface(t) )

    第二个更容易。尤其是这也会导致错误:

    Type t = typeof(List<string>).GetGenericTypeDefinition();
    bool isAssign = typeof(IEnumerable<>).IsAssignableFrom(t);
    
        3
  •  2
  •   LukeH    16 年前

    如果要快速测试特定的封闭泛型类型,例如,检查 List<string> 器具 IEnumerable<string> -然后你可以这样做:

    Type test = typeof(List<string>);
    bool isEnumerable = typeof(IEnumerable<string>).IsAssignableFrom(test);
    

    如果你想要一个更通用的解决方案 IEnumerable<T> 然后你需要用这样的东西来代替:

    Type test = typeof(List<string>);
    bool isEnumerable = test.GetInterfaces().Any(i =>
        i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IEnumerable<>)));
    
        4
  •  1
  •   Henk Holterman    16 年前

    以下返回true,并检查接口:

     enumerable = typeof(List<string>).GetInterfaces()
                   .Contains(typeof(IEnumerable<string>));