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

后端 未结 7 1936
北荒
北荒 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:03

    In Addition to Stefan Steinegger answer: In .NET Core the .IsPrimitive etc. are no longer members of Type, they are now members of TypeInfo. So his solution will then become:

    bool IsSimple(TypeInfo type)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() ==     typeof(Nullable<>))
        {
            // nullable type, check if the nested type is simple.
            return IsSimple((type.GetGenericArguments()[0]).GetTypeInfo());
        }
        return type.IsPrimitive
          || type.IsEnum
          || type.Equals(typeof(string))
          || type.Equals(typeof(decimal));
    }
    

提交回复
热议问题