/// <summary>
/// 转换对象类型
/// </summary>
/// <param name="targetType">转换后类型</param>
/// <param name="source">要转换的对象</param>
/// <returns>返回转换后的对象</returns>
public virtual object ConvertType(object source, Type targetType)
{
// 判断原始对象是否为空或者目标类型是否可以由原始对象直接转换
if (source == null || targetType.IsAssignableFrom(source.GetType()))
{
// 返回原始对象
return source;
}
else
{
// 判断原始对象是否是空字符串
if (source is string && string.IsNullOrWhiteSpace(source as string))
{
// 无法转换,返回默认值
return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
}
else
{
// 判断目标对象是否是可空的泛型值类型
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// 取出可空泛型值类型中的基础值类型
targetType = Nullable.GetUnderlyingType(targetType);
}
// 判断目标对象是否是枚举
if (targetType.IsEnum)
{
// 转换并返回目标对象枚举
return Enum.Parse(targetType, source.ToString());
}
else
{
// 判断原始对象是否是集合
if (source is ICollection)
{
// 将原始对象转换为集合对象
ICollection collection = source as ICollection;
// 判断目标类型是否是数组
if (targetType.IsArray)
{
// 根据目标类型和原始集合对象的长度创建目标对象数组
Array target = Activator.CreateInstance(targetType, collection.Count) as Array;
// 获取目标对象数组的元素类型
Type elementType = targetType.GetElementType();
// 遍历并转换原始集合对象数据到目标对象数组中
int i = 0;
foreach (var item in collection)
{
// 将当前原始数据项转换为目标元素类型并设置到对应的目标对象数组中
target.SetValue(this.ConvertType(item, elementType), i);
i++;
}
// 返回目标对象数组
return target;
}
else
{
// 判断目标类型是否是链表
if (typeof(IList).IsAssignableFrom(targetType))
{
// 根据目标类型创建目标对象链表
IList target = Activator.CreateInstance(targetType) as IList;
// 获取目标对象链表的元素类型
Type elementType = targetType.GetElementType();
// 遍历并转换原始集合对象数据到目标对象链表中
foreach (var item in collection)
{
// 将当前原始数据项转换为目标元素类型并添加到对应的目标对象链表中
target.Add(this.ConvertType(item, elementType));
}
// 返回目标对象链表
return target;
}
}
}
}
// 转换并返回目标对象
return Convert.ChangeType(source, targetType);
}
}
}