using HuanMeng.DotNetCore.AttributeExtend;
using System.Collections;
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Reflection;
namespace HuanMeng.DotNetCore.Utility;
///
/// object转数据字典
///
public static class ObjectExtensions
{
///
/// 用于存储每种类型的属性访问器数组的线程安全缓存。
///
private static readonly ConcurrentDictionary PropertyCache = new();
///
/// 缓存每个属性是否具有 ImagesAttribute 特性。
///
public static readonly ConcurrentDictionary _PropertyCache = new();
///
/// 判断对象是否为原始类型或字符串类型。
///
/// 要检查的对象。
/// 如果对象是原始类型或字符串,返回 true;否则返回 false。
public static bool IsPrimitiveType(object obj) =>
obj is not null && (obj.GetType().IsPrimitive || obj is string or ValueType);
///
/// 判断对象是否为集合类型(不包括字符串)。
///
/// 要检查的对象。
/// 如果对象是集合类型(但不是字符串),返回 true;否则返回 false。
public static bool IsCollectionType(object obj) => obj is IEnumerable && obj is not string;
///
/// 根据对象类型,将对象转换为字典或列表格式,支持可选的路径前缀。
///
/// 要转换的对象。
/// 属性路径的可选前缀。
/// 对象的字典或列表表示形式。
public static object ToDictionaryOrList(this object obj, bool isEnumerable, string prefix = "", Func? imageFunc = null, Func? languageFunc = null)
{
if (obj == null) return null;
return obj switch
{
_ when IsPrimitiveType(obj) => obj,
IEnumerable enumerable => TransformCollection(enumerable, prefix, imageFunc, languageFunc),
_ => TransformObject(obj, isEnumerable, prefix, imageFunc, languageFunc)
};
}
///
/// 将集合对象转换为包含转换项的列表,每个项保留其路径前缀。
///
/// 要转换的集合。
/// 集合中每个属性路径的前缀。
/// 转换后的项列表。
private static List