How to convert a TypeCode to an actual type?

后端 未结 5 1694
一向
一向 2021-02-19 03:14

In the code below I get colType which is a code number for the type. But how would I convert that number into the actual type? Thx!!

for (int j = 0;         


        
5条回答
  •  醉梦人生
    2021-02-19 03:53

    Here's how I like to do it. I prefer using a static table vs. a big switch or reflection for this.

    /// 
    /// Table that maps TypeCode to it's corresponding Type.
    /// 
    static IReadOnlyDictionary TypeCodeToTypeMap = new Dictionary
    {
        { TypeCode.Boolean, typeof(bool) },
        { TypeCode.Byte, typeof(byte) },
        { TypeCode.Char, typeof(char) },
        { TypeCode.DateTime, typeof(DateTime) },
        { TypeCode.DBNull, typeof(DBNull) },
        { TypeCode.Decimal, typeof(decimal) },
        { TypeCode.Double, typeof(double) },
        { TypeCode.Empty, null },
        { TypeCode.Int16, typeof(short) },
        { TypeCode.Int32, typeof(int) },
        { TypeCode.Int64, typeof(long) },
        { TypeCode.Object, typeof(object) },
        { TypeCode.SByte, typeof(sbyte) },
        { TypeCode.Single, typeof(Single) },
        { TypeCode.String, typeof(string) },
        { TypeCode.UInt16, typeof(UInt16) },
        { TypeCode.UInt32, typeof(UInt32) },
        { TypeCode.UInt64, typeof(UInt64) }
    };
    
    /// 
    /// Convert a TypeCode ordinal into it's corresponding Type instance.
    /// 
    public static Type ToType(this TypeCode code)
    {
        Type type = null;
    
        TypeCodeToTypeMap.TryGetValue(code, out type);
    
        return type;
    }
    

提交回复
热议问题