public static void CopyProperties<S, T>(S source, T target)
{
string name = string.Format("{0}_{1}", typeof(S), typeof(T));
object obj = null;
if (!actions.TryGetValue(name, out obj))
{
var copier = CreateCopier<S, T>();
actions.TryAdd(name, copier);
obj = copier;
}
Action<S, T> action = (Action<S, T>)obj;
action(source, target);
}
private static Action<S, T> CreateCopier<S, T>()
{
var target = Expression.Parameter(typeof(T));
var source = Expression.Parameter(typeof(S));
var props1 = typeof(S).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.CanRead).ToList();
var props2 = typeof(T).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<S, T>>(block, source, target).Compile();
}
private static ConcurrentDictionary<string, object> actions = new ConcurrentDictionary<string, object>();
C#实战小技巧(十八):不同类的实体之间赋值(代码示例)
最新推荐文章于 2023-09-26 23:01:44 发布