How to decide a Type is a custom struct?

前端 未结 6 1419
谎友^
谎友^ 2020-12-18 20:14

For a Type, there is a property IsClass in C#, but how to decide a Type is a struct?

Although IsValueType is a ne

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 20:57

    http://msdn.microsoft.com/en-us/library/bfft1t3c.aspx says: IsValueType is true if Type is in {bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort}.

    http://msdn.microsoft.com/en-us/library/system.type.isprimitive%28v=vs.110%29.aspx says: IsPrimitive is true if Type is in {Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single}.

    Than for IsStruct you can use method like this:

    public static bool IsStruct(this Type type)
    {
        return type.IsValueType 
                && !type.IsPrimitive 
                && !type.IsEnum 
                && type != typeof(decimal);
    }
    

提交回复
热议问题