传递过来的数据是obj,知道他的类型Type,那么转换如下:
/// <summary>
/// 把object转换为指定Type类型
/// </summary>
/// <param name="obj">需要转换的对象</param>
/// <param name="type">指定转换的类型</param>
/// <returns>返回object</returns>
private static object ConvertToObject(object obj,Type type)
{
if (type == null) return obj;
if (obj == null) return type.IsValueType ? Activator.CreateInstance(type) : null;
Type underlyingType = Nullable.GetUnderlyingType(type);
//如果待转换对象的类型与目标类型兼容,则无需转换
if(type.IsAssignableFrom(obj.GetType()))
{
return obj;
}
else if((underlyingType??type).IsEnum)//如果待转换的对象的基类型为枚举
{
if (underlyingType == null && string.IsNullOrEmpty(obj.ToString()))
{
return null;
}//可控枚举
else
{
return Enum.Parse(underlyingType ?? type, obj.ToString());
}
}
else if(typeof(IConvertible).IsAssignableFrom(underlyingType??type))//实现了Iconvertible,直接转换
{
try
{
return Convert.ChangeType(obj, underlyingType ?? type, null);
}
catch (Exception)
{
return underlyingType == null ? Activator.CreateInstance(type) : null;
}
}
else
{
TypeConverter converter = TypeDescriptor.GetConverter(type);
if(converter.CanConvertFrom(obj.GetType()))
{
return converter.ConvertFrom(obj);
}
ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
if(constructor!=null)
{
object o = constructor.Invoke(null);
PropertyInfo[] propertys = type.GetProperties();
Type oldType = obj.GetType();
foreach (PropertyInfo item in propertys)
{
PropertyInfo p = oldType.GetProperty(item.Name);
if(item.CanWrite&&p!=null&&p.CanRead)
{
item.SetValue(o,ConvertToObject(p.GetValue(obj,null),item.PropertyType),null);
}
}
return o;
}
}
return obj;
}
网友评论