Advertisement
Guest User

Untitled

a guest
Jul 17th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.05 KB | None | 0 0
  1. private static readonly Dictionary<Type, Func<object, object>> CloneFuncCache =
  2.             new Dictionary<Type, Func<object, object>>();
  3.  
  4.         private object Clone()
  5.         {
  6.             var type = GetType();
  7.             if (!CloneFuncCache.ContainsKey(type))
  8.             {
  9.                 var newExpression = Expression.New(type);
  10.                 var sourceParam = Expression.Parameter(typeof(object));
  11.                 var srcObject = Expression.Convert(sourceParam, type);
  12.                 var propertyBindings = from propertyInfo in type.GetBindingProperties()
  13.                                        let srcProperty = Expression.Property(srcObject, propertyInfo)
  14.                                        select Expression.Bind(propertyInfo, srcProperty);
  15.  
  16.                 var ex = Expression.Lambda<Func<object, object>>(
  17.                     Expression.MemberInit(newExpression, propertyBindings),
  18.                     new[] {sourceParam});
  19.  
  20.                 CloneFuncCache.Add(type, ex.Compile());
  21.             }
  22.  
  23.             return CloneFuncCache[type](this);
  24.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement