开发者

How to determine if Type is a struct?

开发者 https://www.devze.com 2022-12-18 12:21 出处:网络
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 IsPrimitive, IsInterface, etc. but I\'m not sure how to ask for

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 IsPrimitive, IsInterface, etc. but I'm not sure how to ask for a struct?

EDIT: To clarify question. Suppose I have a method:

public Boolean Check(PropertyInfo pi)
{
   return pi.Type.IsStruct;
}开发者_Python百科

What do I write instead of IsStruct?


Type.IsValueType should do the trick.

(pinched from here)


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


putting the comments on Antony Koch 's answer into an extention method:

public static class ReflectionExtensions {
        public static bool IsCustomValueType(this Type type) {            
               return type.IsValueType && !type.IsPrimitive && type.Namespace != null && !type.Namespace.StartsWith("System.");
        }
    }

should work

0

精彩评论

暂无评论...
验证码 换一张
取 消