How do I find out whether an object's type is a subclass of IEnumerable for any value type T?

前端 未结 3 636
北恋
北恋 2021-02-14 21:17

I need to validate an object to see whether it is null, a value type, or IEnumerable where T is a value type. So far I have:

         


        
相关标签:
3条回答
  • 2021-02-14 21:29

    Can you do somethin with GetGenericArguments ?

    0 讨论(0)
  • 2021-02-14 21:54

    My generic contribution that checks if a given type (or its base classes) implements an interface of type T:

    public static bool ImplementsInterface(this Type type, Type interfaceType)
    {
        while (type != null && type != typeof(object))
        {
            if (type.GetInterfaces().Any(@interface => 
                @interface.IsGenericType
                && @interface.GetGenericTypeDefinition() == interfaceType))
            {
                return true;
            }
    
            type = type.BaseType;
        }
    
        return false;
    }
    
    0 讨论(0)
  • 2021-02-14 21:55

    (edit - added value type bits)

    You need to check all the interfaces it implements (note it could in theory implement IEnumerable<T> for multiple T):

    foreach (Type interfaceType in obj.GetType().GetInterfaces())
    {
        if (interfaceType.IsGenericType
            && interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        {
            Type itemType = interfaceType.GetGenericArguments()[0];
            if(!itemType.IsValueType) continue;
            Console.WriteLine("IEnumerable-of-" + itemType.FullName);
        }
    }
    
    0 讨论(0)
提交回复
热议问题