public class SimpleParameter
{
public string ParameterName { get; set; }
public object Value { get; set; }
}
public class ObjectMapper
{
private static ConcurrentDictionary<Type, Func<object, SimpleParameter[]>> _cache = new ConcurrentDictionary<Type, Func<object, SimpleParameter[]>>();
private static readonly ConcurrentDictionary<Type, PropertyInfo[]> _typePropertyCache = new ConcurrentDictionary<Type, PropertyInfo[]>();
public SimpleParameter[] Map(object obj)
{
Type objType = obj.GetType();
return _cache.GetOrAdd(objType, type =>
{
PropertyInfo[] properties = _typePropertyCache.GetOrAdd(objType, t => t.GetProperties());
SimpleParameter[] parameters = new SimpleParameter[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
var p = properties[i];
string propertyName = p.Name;
ParameterExpression paramExpr = Expression.Parameter(typeof(object), "obj");
Expression propertyExpr = Expression.Property(Expression.Convert(paramExpr, objType), p);
Expression convertExpr = Expression.Convert(propertyExpr, typeof(object));
Expression<Func<object, object>> lambdaExpr = Expression.Lambda<Func<object, object>>(convertExpr, paramExpr);
Func<object, object> propertyGetter = lambdaExpr.Compile();
SimpleParameter parameter = new SimpleParameter();
parameter.ParameterName = propertyName;
parameter.Value = propertyGetter(obj);
parameters[i] = parameter;
}
return parameters;
})(obj);
}
}
C# 将object映射成实体类
于 2023-09-26 15:12:17 首次发布