SHARE
TWEET

Untitled

a guest Jul 17th, 2017 47 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.         }
RAW Paste Data
Top