using System;
namespace Common.AssemblyUtil
{
public static class TypeFactory
{
///
/// 将值类型对象转换为指定的数据类型
///
/// 要转换的对象,只支持值类型对象
/// 要转换的数据类型
///
public static object ConvertValueTypeObjectToOriginalType(object obj, Type targetType)
{
if (targetType.IsEnum)
{
return ConvertToEnum(obj, targetType);
}
else if (targetType == typeof(string))
{
return ConvertToString(obj);
}
else if (targetType == typeof(int))
{
return ConvertToInt32(obj);
}
else if (targetType == typeof(short))
{
return ConvertToInt16(obj);
}
else if (targetType == typeof(long))
{
return ConvertToInt64(obj);
}
else if (targetType == typeof(decimal))
{
return ConvertToDecimal(obj);
}
else if (targetType == typeof(Single))
{
return ConvertToSingle(obj);
}
else if (targetType == typeof(double))
{
return ConvertToDouble(obj);
}
else if (targetType == typeof(bool))
{
return ConvertToBoolean(obj);
}
else if (targetType == typeof(DateTime))
{
try
{
return ConvertToDateTime(obj);
}
catch
{
return DateTime.Now;
}
}
//else
//{
// throw new Exceptions.NotSupportedFormatException(targetType);
//}
return null;
}
///
/// 将指定对象转换为指定枚举类型的实例
///
/// 要转换的对象
/// 枚举类型
///
public static object ConvertToEnum(object obj, Type enumType)
{
return Enum.Parse(enumType, obj.ToString(), true);
}
///
/// 转换为字符串格式数据
///
/// 要转换的对象
///
public static object ConvertToString(object obj)
{
return obj.ToString();
}
///
/// 转换为Int16格式数据
///
/// 要转换的对象
///
public static object ConvertToInt16(object obj)
{
return Int16.Parse(obj.ToString());
}
///
/// 转换为Int32格式数据
///
/// 要转换的对象
///
public static object ConvertToInt32(object obj)
{
return Int32.Parse(obj.ToString());
}
///
/// 转换为Int64格式数据
///
/// 要转换的对象
///
public static object ConvertToInt64(object obj)
{
return Int64.Parse(obj.ToString());
}
///
/// 转换为Decimal格式数据
///
/// 要转换的对象
///
public static object ConvertToDecimal(object obj)
{
return Decimal.Parse(obj.ToString());
}
///
/// 转换为Single格式数据
///
/// 要转换的对象
///
public static object ConvertToSingle(object obj)
{
return Single.Parse(obj.ToString());
}
///
/// 转换为Double格式数据
///
/// 要转换的对象
///
public static object ConvertToDouble(object obj)
{
return Double.Parse(obj.ToString());
}
///
/// 转换为Boolean格式数据
///
/// 要转换的对象
///
public static object ConvertToBoolean(object obj)
{
return Boolean.Parse(obj.ToString());
}
public static object ConvertToDateTime(object obj)
{
return DateTime.Parse(obj.ToString());
}
}
}