How do I tell if a type is a “simple” type? i.e. holds a single value

后端 未结 7 1941
北荒
北荒 2020-12-01 02:46
typeof(string).IsPrimitive == false
typeof(int).IsPrimitive == true
typeof(MyClass).IsClass == true
typeof(string).IsClass == true
typeof(string).IsByRef == false
ty         


        
7条回答
  •  遥遥无期
    2020-12-01 03:12

    Modified Mauser's answer a little bit added a method to check whether a property is an collection.

    public static class TypeExtensions
    {
        public static bool IsComplex(this Type type)
        {
            return !type.IsValueType && type != typeof(string);
        }
    
        public static bool IsCollection(this Type type)
        {
            var collectionTypeName = typeof(ICollection<>).Name;
            return type.Name == collectionTypeName || type.GetInterface(collectionTypeName) != null;
        }
    }
    

    Here inside IsCollection(..) we can even keep IEnumerable, but string also inherit IEnumerable. so if you are using IEnumerable, add a check for string also!

    public static class TypeExtensions
        {
    
            public static bool IsComplex(this Type type)
            {
                return !type.IsValueType && type != typeof(string);
            }
    
    
    
            public static bool IsCustomComplex(this Type type)
            {
                var elementType = type.GetCustomElementType();
                return elementType != null && elementType.IsComplex();
            }
    
            public static Type GetCustomElementType(this Type type, object value)
            {
                return value != null 
                    ? value.GetType().GetCustomElementType() 
                    : type.GetCustomElementType();
            }
    
            public static Type GetCustomElementType(this Type type)
            {
                return type.IsCollection()
                    ? type.IsArray
                        ? type.GetElementType()
                        : type.GetGenericArguments()[0]
                    : type;
            }
    
    
            public static bool IsCustomComplex(this Type type, object value)
            {
                return value != null
                    ? value.GetType().IsCustomComplex()
                    : type.IsCustomComplex();
            }
    
    
            public static bool IsCollection(this Type type)
            {
                var collectionTypeName = typeof(IEnumerable<>).Name;
                return (type.Name == collectionTypeName || type.GetInterface(typeof(IEnumerable<>).Name) != null ||
                        type.IsArray) && type != typeof(string);
            }
    
            public static bool HasDefaultConstructor(this Type type)
            {
                return type.IsValueType || type.GetConstructor(Type.EmptyTypes) != null;
            }
    
        }
    

提交回复
热议问题