using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
namespace Uilt
{
//返回类
public static class ObjectHelper
{
//简单类型转换
public static T As<T>(this object value, T defaultValue = default(T))
{
T res = defaultValue;
if (value == null)//为null返回默认值
{
return res;
}
object resValue = null;
Type fromType = value.GetType();
Type toType = typeof(T);
TypeCode fromTypeCode = Type.GetTypeCode(fromType);//来源类型
TypeCode toTypeCode = Type.GetTypeCode(toType);//结果类型
try
{
switch (toTypeCode)
{
case TypeCode.Boolean:
#region bool 转换
switch (fromTypeCode)
{
case TypeCode.SByte:
resValue = (sbyte)value > 0;
break;
case TypeCode.Byte:
resValue = (byte)value > 0;
break;
case TypeCode.Int16:
resValue = (short)value > 0;
break;
case TypeCode.UInt16:
resValue = (ushort)value > 0;
break;
case TypeCode.Int32:
resValue = (int)value > 0;
break;
case TypeCode.UInt32:
resValue = (uint)value != 0;
break;
case TypeCode.Int64:
resValue = (long)value > 0L;
break;
case TypeCode.UInt64:
resValue = (ulong)value > 0L;
break;
case TypeCode.String:
try
{
resValue = int.Parse((string)value) > 0;
}
catch
{
}
break;
}
resValue = ((IConvertible)value).ToBoolean(null);
#endregion
break;
case TypeCode.Char:
resValue = ((IConvertible)value).ToChar(null);
break;
case TypeCode.SByte:
resValue = ((IConvertible)value).ToSByte(null);
break;
case TypeCode.Byte:
resValue = ((IConvertible)value).ToByte(null);
break;
case TypeCode.Int16:
resValue = ((IConvertible)value).ToInt16(null);
break;
case TypeCode.UInt16:
resValue = ((IConvertible)value).ToUInt16(null);
break;
case TypeCode.Int32:
resValue = ((IConvertible)value).ToInt32(null);
break;
case TypeCode.UInt32:
resValue = ((IConvertible)value).ToUInt32(null);
break;
case TypeCode.Int64:
resValue = ((IConvertible)value).ToInt64(null);
break;
case TypeCode.UInt64:
resValue = ((IConvertible)value).ToUInt64(null);
break;
case TypeCode.Single:
resValue = ((IConvertible)value).ToSingle(null);
break;
case TypeCode.Double:
resValue = ((IConvertible)value).ToDouble(null);
break;
case TypeCode.Decimal:
resValue = ((IConvertible)value).ToDecimal(null);
break;
case TypeCode.DateTime:
resValue = ((IConvertible)value).ToDateTime(null);
break;
case TypeCode.String:
resValue = (value == null ? string.Empty : ((IConvertible)value).ToString(null));
break;
default:
resValue = value;
break;
}
if (resValue != null)
{
res = (T)resValue;
}
}
catch (Exception)
{
}
return res;
}
}
}