数据类型转换

/// <summary>
/// 数据类型转换
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="value">源数据</param>
/// <param name="defaultValue">默认值</param>
/// <returns>结果</returns>
public static T To<T>(object value, T defaultValue)
{
/* T obj;
try {
if (value == null) {
return defaultValue;
}
obj = (T)Convert.ChangeType(value, typeof(T));
if (obj == null) {
obj = defaultValue;
}
} catch {
obj = defaultValue;
}
return obj;*/
T obj = default(T);
try
{
if (value == null)
{
return defaultValue;
}
var valueType = value.GetType();
var targetType = typeof(T);
tag1:
if (valueType == targetType)
{
return (T)value;
}
if (targetType.IsEnum)
{
if (value is string)
{
return (T)System.Enum.Parse(targetType, value as string);
}
else
{
return (T)System.Enum.ToObject(targetType, value);
}
}
if (targetType == typeof(Guid) && value is string)
{
object obj1 = new Guid(value as string);
return (T)obj1;

}
if (targetType == typeof(DateTime) && value is string)
{
DateTime d1;
if (DateTime.TryParse(value as string, out d1))
{
object obj1 = d1;
return (T)obj1;
}


}
if (targetType.IsGenericType)
{
if (targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
targetType = Nullable.GetUnderlyingType(targetType);
goto tag1;
}
}
if (value is IConvertible)
{
obj = (T)Convert.ChangeType(value, typeof(T));
}

if (obj == null)
{
obj = defaultValue;
}
}
catch
{
obj = defaultValue;
}
return obj;
}

原文地址:https://www.cnblogs.com/guzhengtao/p/20180706_1553.html