Checking if Type or instance implements IEnumerable regardless of Type T

后端 未结 3 794
無奈伤痛
無奈伤痛 2020-12-16 09:38

I\'m doing a heavy bit of reflection in my current project, and I\'m trying to provide a few helper methods just to keep everything tidy.

I\'d like to provide a pair

相关标签:
3条回答
  • 2020-12-16 09:55

    To check if some type implements IEnumerable regardless of T one needs to check the GenericTypeDefinition.

    public static bool IsIEnumerableOfT(this Type type)
    {
        return type.GetInterfaces().Any(x => x.IsGenericType
               && x.GetGenericTypeDefinition() == typeof(IEnumerable<>));
    }
    
    0 讨论(0)
  • 2020-12-16 10:03

    In addition to Type.IsAssignableFrom(Type), you can also use Type.GetInterfaces():

    public static bool ImplementsInterface(this Type type, Type interface)
    {
        bool implemented = type.GetInterfaces().Contains(interface);
        return implemented;
    }
    

    That way, if you wanted to check multiple interfaces you could easily modify ImplementsInterface to take multiple interfaces.

    0 讨论(0)
  • 2020-12-16 10:10

    The following line

    return (type is IEnumerable);
    

    is asking "if an instance of Type, type is IEnumerable", which clearly it is not.

    You want to do is:

    return typeof(IEnumerable).IsAssignableFrom(type);
    
    0 讨论(0)
提交回复
热议问题