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

前端 未结 3 746
你的背包
你的背包 2021-02-14 21:03

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:44

    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;
    }
    

提交回复
热议问题