How to determine if Type is a struct?

前端 未结 3 795
-上瘾入骨i
-上瘾入骨i 2021-01-17 19:22

Given a PropertyInfo instance, which has a Type property, how does one determine if it is a struct? I found there are properties such as IsPr

3条回答
  •  生来不讨喜
    2021-01-17 19:48

    Structs and enums (IsEnum) fall under the superset called value types (IsValueType). Primitive types (IsPrimitive) are a subset of struct. Which means all primitive types are structs but not vice versa; for eg, int is a primitive type as well as struct, but decimal is only a struct, not a primitive type.

    So you see the only missing property there is that of a struct. Easy to write one:

    public bool IsStruct(this Type type)
    {
       return type.IsValueType && !type.IsEnum;
    }
    

提交回复
热议问题