using System; using System.ComponentModel; using System.Data; namespace AIMSExtension { public class TypeHelper { public static Type ConvertTypeToBaseType(Type t) { //判断convertsionType类型是否为泛型,因为nullable是泛型类, //判断convertsionType是否为nullable泛型类 if (t.IsGenericType &&( t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))|| t.GetGenericTypeDefinition().Equals(typeof(DBNull)))) { //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换 NullableConverter nullableConverter = new NullableConverter(t); //将convertsionType转换为nullable对的基础基元类型 t = nullableConverter.UnderlyingType; } return t; } public static object GetDefalutValue(Type t) { if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { return null; } var code = Type.GetTypeCode(t); switch (code) { case TypeCode.Boolean: return default(bool); case TypeCode.Byte: return default(byte); case TypeCode.DateTime: return default(DateTime); case TypeCode.Decimal: return default(decimal); case TypeCode.Double: return default(double); case TypeCode.Int16: return default(Int16); case TypeCode.Int32: return default(Int32); case TypeCode.Int64: return default(Int64); case TypeCode.SByte: return default(SByte); case TypeCode.Single: return default(Single); case TypeCode.String: return default(String); case TypeCode.UInt16: return default(UInt16); case TypeCode.UInt32: return default(UInt32); case TypeCode.UInt64: return default(UInt64); case TypeCode.Object: return null; default: return null; } } public static SqlDbType ConvertTypeToSqlDbType(Type t) { //判断convertsionType类型是否为泛型,因为nullable是泛型类, //判断convertsionType是否为nullable泛型类 if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换 NullableConverter nullableConverter = new NullableConverter(t); //将convertsionType转换为nullable对的基础基元类型 t = nullableConverter.UnderlyingType; } var code = Type.GetTypeCode(t); switch (code) { case TypeCode.Boolean: return SqlDbType.Bit; case TypeCode.Byte: return SqlDbType.TinyInt; case TypeCode.DateTime: return SqlDbType.DateTime; case TypeCode.Decimal: return SqlDbType.Decimal; case TypeCode.Double: return SqlDbType.Float; case TypeCode.Int16: return SqlDbType.SmallInt; case TypeCode.Int32: return SqlDbType.Int; case TypeCode.Int64: return SqlDbType.BigInt; case TypeCode.SByte: return SqlDbType.TinyInt; case TypeCode.Single: return SqlDbType.Real; case TypeCode.String: return SqlDbType.NVarChar; case TypeCode.UInt16: return SqlDbType.SmallInt; case TypeCode.UInt32: return SqlDbType.Int; case TypeCode.UInt64: return SqlDbType.BigInt; case TypeCode.Object: return SqlDbType.Variant; default: if (t == typeof(byte[])) { return SqlDbType.Binary; } return SqlDbType.Variant; } } } }