using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Security.AccessControl; namespace ChangkeTec.Utils { public static class TransHelper { private static readonly Func Cache = GetFunc(); private static Func GetFunc() { var parameterExpression = Expression.Parameter(typeof(TIn), "p"); var memberBindingList = new List(); foreach (var item in typeof(TOut).GetProperties()) { if (!item.CanWrite) continue; var inProp = typeof(TIn).GetProperty(item.Name); if (inProp==null) continue; var outProp = Expression.Property(parameterExpression, inProp); MemberBinding memberBinding = Expression.Bind(item, outProp); memberBindingList.Add(memberBinding); } var memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray()); var lambda = Expression.Lambda>(memberInitExpression, new ParameterExpression[] { parameterExpression }); return lambda.Compile(); } public static TOut Trans(TIn tIn) { return Cache(tIn); } } }