代码之家  ›  专栏  ›  技术社区  ›  Paul Hollingsworth

.NET反射:检测IEnumerable<T>

  •  11
  • Paul Hollingsworth  · 技术社区  · 16 年前

    我能想到的最好办法是:

    // theType might be typeof(IEnumerable<string>) for example... or it might not
    bool isGenericEnumerable = theType.GetGenericTypeDefinition() == typeof(IEnumerable<object>).GetGenericTypeDefinition()
    if(isGenericEnumerable)
    {
        Type enumType = theType.GetGenericArguments()[0];
        etc. ...// enumType is now typeof(string) 
    

    3 回复  |  直到 16 年前
        1
  •  22
  •   Fabrício Matté    16 年前

    你可以用

    if(theType.IsGenericType && theType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
    {
        Type underlyingType = theType.GetGenericArguments()[0];
        //do something here
    }
    

    编辑:添加了IsGenericType检查,感谢您的有用评论

        2
  •  4
  •   Paul Turner    16 年前

    IEnumerable<T> 界面

    Type type = typeof(ICollection<string>);
    
    bool isEnumerable = type.GetInterfaces()       // Get all interfaces.
        .Where(i => i.IsGenericType)               // Filter to only generic.
        .Select(i => i.GetGenericTypeDefinition()) // Get their generic def.
        .Where(i => i == typeof(IEnumerable<>))    // Get those which match.
        .Count() > 0;
    

    它将适用于任何接口,但是 如果您传入的类型为 IEnumerable<T> .

        3
  •  2
  •   Lucero    16 年前

    GetGenericTypeDefinition() 因此,对于非泛型类型,请首先检查 IsGenericType .

    我不确定是否要检查类型是否实现泛型 IEnumerable<> IEnumerable<&燃气轮机; interfaceType 第二种情况是:

    if (typeof(IEnumerable).IsAssignableFrom(type)) {
        foreach (Type interfaceType in type.GetInterfaces()) {
            if (interfaceType.IsGenericType && (interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))) {
                Console.WriteLine("{0} implements {1} enumerator", type.FullName, interfaceType.FullName); // is a match
            }
        }
    }