1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- 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
- {
- /// <summary>
- /// 在两个不同的类型之间,快速的拷贝
- /// </summary>
- public static class FastEntityCopy
- {
- static ConcurrentDictionary<string, object> actions = new ConcurrentDictionary<string, object>();
- static Action<TSource, TTarget> CreateCopier<TSource, TTarget>()
- {
- 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<Action<TSource, TTarget>>(block, source, target).Compile();
- }
- /// <summary>
- /// 快速的拷贝同名公共属性。忽略差异的字段。
- /// </summary>
- /// <typeparam name="S"></typeparam>
- /// <typeparam name="T"></typeparam>
- /// <param name="from"></param>
- /// <param name="to"></param>
- public static void Copy<TSource, TTarget>(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<TSource, TTarget>();
- actions.TryAdd(name, ff);
- obj = ff;
- }
- Action<TSource, TTarget> act = (Action<TSource, TTarget>)obj;
- act(from, to);
- }
- }
- }
|