using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace NXWMS.Code.Entitys { /// /// 在两个不同的类型之间,快速的拷贝 /// public static class FastEntityCopy { static ConcurrentDictionary actions = new ConcurrentDictionary(); static Action CreateCopier() { var target = Expression.Parameter(typeof(TTarget)); var source = Expression.Parameter(typeof(TSource)); var props1 = typeof(TSource).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.CanRead).ToList(); var props2 = typeof(TTarget).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.CanWrite).ToList(); var props = props1.Where(x => props2.Where(y => y.Name == x.Name).Count() > 0); var block = Expression.Block( from p in props select Expression.Assign(Expression.Property(target, p.Name), Expression.Property(source, p.Name))); return Expression.Lambda>(block, source, target).Compile(); } /// /// 快速的拷贝同名公共属性。忽略差异的字段。 /// /// /// /// /// public static void Copy(TSource from, TTarget to) { string name = string.Format("{0}_{1}", typeof(TSource), typeof(TTarget)); object obj; if (!actions.TryGetValue(name, out obj)) { var ff = CreateCopier(); actions.TryAdd(name, ff); obj = ff; } Action act = (Action)obj; act(from, to); } } }