C# 将object映射成实体类

    public class SimpleParameter
    {
        public string ParameterName { get; set; }
        public object Value { get; set; }
    }
     public class ObjectMapper
    {
        private static ConcurrentDictionary> _cache = new ConcurrentDictionary>();
        private static readonly ConcurrentDictionary typePropertyCache = new ConcurrentDictionary();

        public SimpleParameter[] Map(object obj)
        {
            if (obj == null)
                return new SimpleParameter[0];

            Type objType = obj.GetType();
            Func func;
            if (_cache.TryGetValue(objType, out func))
            {
                return func(obj);
            }

            PropertyInfo[] properties;
            if (!typePropertyCache.TryGetValue(objType, out properties))
            {
                properties = objType.GetProperties();
                typePropertyCache.TryAdd(objType, properties);
            }

            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> lambdaExpr = Expression.Lambda>(convertExpr, paramExpr);
                Func propertyGetter = lambdaExpr.Compile();

                SimpleParameter parameter = new SimpleParameter();
                parameter.ParameterName = propertyName;
                parameter.Value = propertyGetter(obj);
                parameters[i]= parameter;
            }

            _cache.TryAdd(objType, (o) => parameters);

            return parameters;
        }
    }

你可能感兴趣的:(c#)