代码改变世界

步步为营:Asp.Net Type与DBType之间的转换

2011-12-20 16:59  薛凯凯圆滚滚  阅读(369)  评论(0编辑  收藏  举报

今天在建立框架的时候看了需要Type转换成DBType,于是写了两个方法。

获取DBType枚举。

public static DbType TypeToDbType(Type t) 
{
DbType dbt;
try
{
dbt = (DbType)Enum.Parse(typeof(DbType), t.Name);
}
catch
{
dbt = DbType.Object;
}
return dbt;
}

获取 Type Class

public static Type ConvertType(DbType dbType) 
{
Type toReturn = typeof(DBNull);

switch (dbType)
{
case DbType.UInt64:
toReturn = typeof(UInt64);
break;

case DbType.Int64:
toReturn = typeof(Int64);
break;

case DbType.Int32:
toReturn = typeof(Int32);
break;

case DbType.UInt32:
toReturn = typeof(UInt32);
break;

case DbType.Single:
toReturn = typeof(float);
break;

case DbType.Date:
case DbType.DateTime:
case DbType.Time:
toReturn = typeof(DateTime);
break;

case DbType.String:
case DbType.StringFixedLength:
case DbType.AnsiString:
case DbType.AnsiStringFixedLength:
toReturn = typeof(string);
break;

case DbType.UInt16:
toReturn = typeof(UInt16);
break;

case DbType.Int16:
toReturn = typeof(Int16);
break;

case DbType.SByte:
toReturn = typeof(byte);
break;

case DbType.Object:
toReturn = typeof(object);
break;

case DbType.VarNumeric:
case DbType.Decimal:
toReturn = typeof(decimal);
break;

case DbType.Currency:
toReturn = typeof(double);
break;

case DbType.Binary:
toReturn = typeof(byte[]);
break;

case DbType.Double:
toReturn = typeof(Double);
break;

case DbType.Guid:
toReturn = typeof(Guid);
break;

case DbType.Boolean:
toReturn = typeof(bool);
break;
}

return toReturn;
}