using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Serein.Library.Utils
{
///
/// 对象转换工具类
///
public static class ObjectConvertHelper
{
///
/// 父类转为子类
///
/// 父类对象
/// 子类类型
///
public static object ConvertParentToChild(object parent, Type childType)
{
var child = Activator.CreateInstance(childType);
var parentType = parent.GetType();
// 复制父类属性
foreach (var prop in parentType.GetProperties())
{
if (prop.CanWrite)
{
var value = prop.GetValue(parent);
childType.GetProperty(prop.Name)?.SetValue(child, value);
}
}
return child;
}
///
/// 集合类型转换为Array/List
///
///
///
///
///
public static object ConvertToEnumerableType(object obj, Type targetType)
{
// 获取目标类型的元素类型
Type targetElementType = targetType.IsArray
? targetType.GetElementType()
: targetType.GetGenericArguments().FirstOrDefault();
if (targetElementType == null)
throw new InvalidOperationException("无法获取目标类型的元素类型");
// 检查输入对象是否为集合类型
if (obj is IEnumerable collection)
{
// 判断目标类型是否是数组
if (targetType.IsArray)
{
var toArrayMethod = typeof(Enumerable).GetMethod("ToArray").MakeGenericMethod(targetElementType);
return toArrayMethod.Invoke(null, new object[] { collection });
}
// 判断目标类型是否是 List
else if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(List<>))
{
var toListMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(targetElementType);
return toListMethod.Invoke(null, new object[] { collection });
}
// 判断目标类型是否是 HashSet
else if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(HashSet<>))
{
var toHashSetMethod = typeof(Enumerable).GetMethod("ToHashSet").MakeGenericMethod(targetElementType);
return toHashSetMethod.Invoke(null, new object[] { collection });
}
// 其他类型可以扩展类似的处理
}
throw new InvalidOperationException("输入对象不是集合或目标类型不支持");
}
}
}