DeepCopyExt.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Reflection;
  6. namespace Masuit.Tools
  7. {
  8. /// <summary>
  9. ///
  10. /// </summary>
  11. public static class DeepCopyExt
  12. {
  13. private static readonly object IsStructTypeToDeepCopyDictionaryLocker = new object();
  14. private static Dictionary<Type, bool> _isStructTypeToDeepCopyDictionary = new Dictionary<Type, bool>();
  15. private static readonly object CompiledCopyFunctionsDictionaryLocker = new object();
  16. private static Dictionary<Type, Func<object, Dictionary<object, object>, object>> _compiledCopyFunctionsDictionary = new Dictionary<Type, Func<object, Dictionary<object, object>, object>>();
  17. private static readonly Type ObjectType = typeof(object);
  18. private static readonly Type ObjectDictionaryType = typeof(Dictionary<object, object>);
  19. /// <summary>
  20. /// 深克隆
  21. /// </summary>
  22. /// <param name="original">原始对象</param>
  23. /// <param name="copiedReferencesDict">需要被引用传递的对象(Keys: 原始对象, Values: 副本对象).</param>
  24. /// <returns></returns>
  25. public static T DeepClone<T>(this T original, Dictionary<object, object> copiedReferencesDict = null)
  26. {
  27. return (T)DeepCopyObj(original, false, copiedReferencesDict ?? new Dictionary<object, object>(new ReferenceEqualityComparer()));
  28. }
  29. private static object DeepCopyObj(object original, bool forceDeepCopy, Dictionary<object, object> copiedReferencesDict)
  30. {
  31. if (original == null)
  32. {
  33. return null;
  34. }
  35. var type = original.GetType();
  36. if (IsDelegate(type))
  37. {
  38. return null;
  39. }
  40. if (!forceDeepCopy && !IsTypeToDeepCopy(type))
  41. {
  42. return original;
  43. }
  44. if (copiedReferencesDict.TryGetValue(original, out var alreadyCopiedObject))
  45. {
  46. return alreadyCopiedObject;
  47. }
  48. if (type == ObjectType)
  49. {
  50. return new object();
  51. }
  52. var compiledCopyFunction = GetOrCreateCompiledLambdaCopyFunction(type);
  53. object copy = compiledCopyFunction(original, copiedReferencesDict);
  54. return copy;
  55. }
  56. private static Func<object, Dictionary<object, object>, object> GetOrCreateCompiledLambdaCopyFunction(Type type)
  57. {
  58. if (!_compiledCopyFunctionsDictionary.TryGetValue(type, out var compiledCopyFunction))
  59. {
  60. lock (CompiledCopyFunctionsDictionaryLocker)
  61. {
  62. if (!_compiledCopyFunctionsDictionary.TryGetValue(type, out compiledCopyFunction))
  63. {
  64. var uncompiledCopyFunction = CreateCompiledLambdaCopyFunctionForType(type);
  65. compiledCopyFunction = uncompiledCopyFunction.Compile();
  66. var dictionaryCopy = _compiledCopyFunctionsDictionary.ToDictionary(pair => pair.Key, pair => pair.Value);
  67. dictionaryCopy.Add(type, compiledCopyFunction);
  68. _compiledCopyFunctionsDictionary = dictionaryCopy;
  69. }
  70. }
  71. }
  72. return compiledCopyFunction;
  73. }
  74. private static Expression<Func<object, Dictionary<object, object>, object>> CreateCompiledLambdaCopyFunctionForType(Type type)
  75. {
  76. InitializeExpressions(type, out var inputParameter, out var inputDictionary, out var outputVariable, out var boxingVariable, out var endLabel, out var variables, out var expressions);
  77. IfNullThenReturnNullExpression(inputParameter, endLabel, expressions);
  78. MemberwiseCloneInputToOutputExpression(type, inputParameter, outputVariable, expressions);
  79. if (IsClassOtherThanString(type))
  80. {
  81. StoreReferencesIntoDictionaryExpression(inputParameter, inputDictionary, outputVariable, expressions);
  82. }
  83. FieldsCopyExpressions(type, inputParameter, inputDictionary, outputVariable, boxingVariable, expressions);
  84. if (IsArray(type) && IsTypeToDeepCopy(type.GetElementType()))
  85. {
  86. CreateArrayCopyLoopExpression(type, inputParameter, inputDictionary, outputVariable, variables, expressions);
  87. }
  88. var lambda = CombineAllIntoLambdaFunctionExpression(inputParameter, inputDictionary, outputVariable, endLabel, variables, expressions);
  89. return lambda;
  90. }
  91. private static void InitializeExpressions(Type type, out ParameterExpression inputParameter, out ParameterExpression inputDictionary, out ParameterExpression outputVariable, out ParameterExpression boxingVariable, out LabelTarget endLabel, out List<ParameterExpression> variables, out List<Expression> expressions)
  92. {
  93. inputParameter = Expression.Parameter(ObjectType);
  94. inputDictionary = Expression.Parameter(ObjectDictionaryType);
  95. outputVariable = Expression.Variable(type);
  96. boxingVariable = Expression.Variable(ObjectType);
  97. endLabel = Expression.Label();
  98. variables = new List<ParameterExpression>();
  99. expressions = new List<Expression>();
  100. variables.Add(outputVariable);
  101. variables.Add(boxingVariable);
  102. }
  103. private static void IfNullThenReturnNullExpression(ParameterExpression inputParameter, LabelTarget endLabel, List<Expression> expressions)
  104. {
  105. var ifNullThenReturnNullExpression = Expression.IfThen(Expression.Equal(inputParameter, Expression.Constant(null, ObjectType)), Expression.Return(endLabel));
  106. expressions.Add(ifNullThenReturnNullExpression);
  107. }
  108. private static void MemberwiseCloneInputToOutputExpression(Type type, ParameterExpression inputParameter, ParameterExpression outputVariable, List<Expression> expressions)
  109. {
  110. var memberwiseCloneMethod = ObjectType.GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);
  111. var memberwiseCloneInputExpression = Expression.Assign(outputVariable, Expression.Convert(Expression.Call(inputParameter, memberwiseCloneMethod), type));
  112. expressions.Add(memberwiseCloneInputExpression);
  113. }
  114. private static void StoreReferencesIntoDictionaryExpression(ParameterExpression inputParameter, ParameterExpression inputDictionary, ParameterExpression outputVariable, List<Expression> expressions)
  115. {
  116. var storeReferencesExpression = Expression.Assign(Expression.Property(inputDictionary, ObjectDictionaryType.GetProperty("Item"), inputParameter), Expression.Convert(outputVariable, ObjectType));
  117. expressions.Add(storeReferencesExpression);
  118. }
  119. private static Expression<Func<object, Dictionary<object, object>, object>> CombineAllIntoLambdaFunctionExpression(ParameterExpression inputParameter, ParameterExpression inputDictionary, ParameterExpression outputVariable, LabelTarget endLabel, List<ParameterExpression> variables, List<Expression> expressions)
  120. {
  121. expressions.Add(Expression.Label(endLabel));
  122. expressions.Add(Expression.Convert(outputVariable, ObjectType));
  123. var finalBody = Expression.Block(variables, expressions);
  124. var lambda = Expression.Lambda<Func<object, Dictionary<object, object>, object>>(finalBody, inputParameter, inputDictionary);
  125. return lambda;
  126. }
  127. private static void CreateArrayCopyLoopExpression(Type type, ParameterExpression inputParameter, ParameterExpression inputDictionary, ParameterExpression outputVariable, List<ParameterExpression> variables, List<Expression> expressions)
  128. {
  129. var rank = type.GetArrayRank();
  130. var indices = GenerateIndices(rank);
  131. variables.AddRange(indices);
  132. var elementType = type.GetElementType();
  133. var assignExpression = ArrayFieldToArrayFieldAssignExpression(inputParameter, inputDictionary, outputVariable, elementType, type, indices);
  134. Expression forExpression = assignExpression;
  135. for (int dimension = 0; dimension < rank; dimension++)
  136. {
  137. var indexVariable = indices[dimension];
  138. forExpression = LoopIntoLoopExpression(inputParameter, indexVariable, forExpression, dimension);
  139. }
  140. expressions.Add(forExpression);
  141. }
  142. private static List<ParameterExpression> GenerateIndices(int arrayRank)
  143. {
  144. var indices = new List<ParameterExpression>();
  145. for (int i = 0; i < arrayRank; i++)
  146. {
  147. var indexVariable = Expression.Variable(typeof(int));
  148. indices.Add(indexVariable);
  149. }
  150. return indices;
  151. }
  152. private static BinaryExpression ArrayFieldToArrayFieldAssignExpression(ParameterExpression inputParameter, ParameterExpression inputDictionary, ParameterExpression outputVariable, Type elementType, Type arrayType, List<ParameterExpression> indices)
  153. {
  154. var indexTo = Expression.ArrayAccess(outputVariable, indices);
  155. var indexFrom = Expression.ArrayIndex(Expression.Convert(inputParameter, arrayType), indices);
  156. var forceDeepCopy = elementType != ObjectType;
  157. var rightSide = Expression.Convert(Expression.Call(DeepCopyByExpressionTreeObjMethod, Expression.Convert(indexFrom, ObjectType), Expression.Constant(forceDeepCopy, typeof(bool)), inputDictionary), elementType);
  158. var assignExpression = Expression.Assign(indexTo, rightSide);
  159. return assignExpression;
  160. }
  161. private static BlockExpression LoopIntoLoopExpression(ParameterExpression inputParameter, ParameterExpression indexVariable, Expression loopToEncapsulate, int dimension)
  162. {
  163. var lengthVariable = Expression.Variable(typeof(int));
  164. var endLabelForThisLoop = Expression.Label();
  165. var newLoop = Expression.Loop(Expression.Block(new ParameterExpression[0], Expression.IfThen(Expression.GreaterThanOrEqual(indexVariable, lengthVariable), Expression.Break(endLabelForThisLoop)), loopToEncapsulate, Expression.PostIncrementAssign(indexVariable)), endLabelForThisLoop);
  166. var lengthAssignment = GetLengthForDimensionExpression(lengthVariable, inputParameter, dimension);
  167. var indexAssignment = Expression.Assign(indexVariable, Expression.Constant(0));
  168. return Expression.Block(new[]
  169. {
  170. lengthVariable
  171. }, lengthAssignment, indexAssignment, newLoop);
  172. }
  173. private static BinaryExpression GetLengthForDimensionExpression(ParameterExpression lengthVariable, ParameterExpression inputParameter, int i)
  174. {
  175. var getLengthMethod = typeof(Array).GetMethod("GetLength", BindingFlags.Public | BindingFlags.Instance);
  176. var dimensionConstant = Expression.Constant(i);
  177. return Expression.Assign(lengthVariable, Expression.Call(Expression.Convert(inputParameter, typeof(Array)), getLengthMethod, new[]
  178. {
  179. dimensionConstant
  180. }));
  181. }
  182. private static void FieldsCopyExpressions(Type type, ParameterExpression inputParameter, ParameterExpression inputDictionary, ParameterExpression outputVariable, ParameterExpression boxingVariable, List<Expression> expressions)
  183. {
  184. var fields = GetAllRelevantFields(type);
  185. var readonlyFields = fields.Where(f => f.IsInitOnly).ToList();
  186. var writableFields = fields.Where(f => !f.IsInitOnly).ToList();
  187. bool shouldUseBoxing = readonlyFields.Any();
  188. if (shouldUseBoxing)
  189. {
  190. var boxingExpression = Expression.Assign(boxingVariable, Expression.Convert(outputVariable, ObjectType));
  191. expressions.Add(boxingExpression);
  192. }
  193. foreach (var field in readonlyFields)
  194. {
  195. if (IsDelegate(field.FieldType))
  196. {
  197. ReadonlyFieldToNullExpression(field, boxingVariable, expressions);
  198. }
  199. else
  200. {
  201. ReadonlyFieldCopyExpression(type, field, inputParameter, inputDictionary, boxingVariable, expressions);
  202. }
  203. }
  204. if (shouldUseBoxing)
  205. {
  206. var unboxingExpression = Expression.Assign(outputVariable, Expression.Convert(boxingVariable, type));
  207. expressions.Add(unboxingExpression);
  208. }
  209. foreach (var field in writableFields)
  210. {
  211. if (IsDelegate(field.FieldType))
  212. {
  213. WritableFieldToNullExpression(field, outputVariable, expressions);
  214. }
  215. else
  216. {
  217. WritableFieldCopyExpression(type, field, inputParameter, inputDictionary, outputVariable, expressions);
  218. }
  219. }
  220. }
  221. private static FieldInfo[] GetAllRelevantFields(Type type, bool forceAllFields = false)
  222. {
  223. var fieldsList = new List<FieldInfo>();
  224. var typeCache = type;
  225. while (typeCache != null)
  226. {
  227. fieldsList.AddRange(typeCache.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Where(field => forceAllFields || IsTypeToDeepCopy(field.FieldType)));
  228. typeCache = typeCache.BaseType;
  229. }
  230. return fieldsList.ToArray();
  231. }
  232. private static FieldInfo[] GetAllFields(Type type)
  233. {
  234. return GetAllRelevantFields(type, true);
  235. }
  236. private static readonly Type FieldInfoType = typeof(FieldInfo);
  237. private static readonly MethodInfo SetValueMethod = FieldInfoType.GetMethod("SetValue", new[]
  238. {
  239. ObjectType,
  240. ObjectType
  241. });
  242. private static void ReadonlyFieldToNullExpression(FieldInfo field, ParameterExpression boxingVariable, List<Expression> expressions)
  243. {
  244. var fieldToNullExpression = Expression.Call(Expression.Constant(field), SetValueMethod, boxingVariable, Expression.Constant(null, field.FieldType));
  245. expressions.Add(fieldToNullExpression);
  246. }
  247. private static readonly Type ThisType = typeof(DeepCopyExt);
  248. private static readonly MethodInfo DeepCopyByExpressionTreeObjMethod = ThisType.GetMethod("DeepCopyByExpressionTreeObj", BindingFlags.NonPublic | BindingFlags.Static);
  249. private static void ReadonlyFieldCopyExpression(Type type, FieldInfo field, ParameterExpression inputParameter, ParameterExpression inputDictionary, ParameterExpression boxingVariable, List<Expression> expressions)
  250. {
  251. var fieldFrom = Expression.Field(Expression.Convert(inputParameter, type), field);
  252. var forceDeepCopy = field.FieldType != ObjectType;
  253. var fieldDeepCopyExpression = Expression.Call(Expression.Constant(field, FieldInfoType), SetValueMethod, boxingVariable, Expression.Call(DeepCopyByExpressionTreeObjMethod, Expression.Convert(fieldFrom, ObjectType), Expression.Constant(forceDeepCopy, typeof(bool)), inputDictionary));
  254. expressions.Add(fieldDeepCopyExpression);
  255. }
  256. private static void WritableFieldToNullExpression(FieldInfo field, ParameterExpression outputVariable, List<Expression> expressions)
  257. {
  258. var fieldTo = Expression.Field(outputVariable, field);
  259. var fieldToNullExpression = Expression.Assign(fieldTo, Expression.Constant(null, field.FieldType));
  260. expressions.Add(fieldToNullExpression);
  261. }
  262. private static void WritableFieldCopyExpression(Type type, FieldInfo field, ParameterExpression inputParameter, ParameterExpression inputDictionary, ParameterExpression outputVariable, List<Expression> expressions)
  263. {
  264. var fieldFrom = Expression.Field(Expression.Convert(inputParameter, type), field);
  265. var fieldType = field.FieldType;
  266. var fieldTo = Expression.Field(outputVariable, field);
  267. var forceDeepCopy = field.FieldType != ObjectType;
  268. var fieldDeepCopyExpression = Expression.Assign(fieldTo, Expression.Convert(Expression.Call(DeepCopyByExpressionTreeObjMethod, Expression.Convert(fieldFrom, ObjectType), Expression.Constant(forceDeepCopy, typeof(bool)), inputDictionary), fieldType));
  269. expressions.Add(fieldDeepCopyExpression);
  270. }
  271. private static bool IsArray(Type type)
  272. {
  273. return type.IsArray;
  274. }
  275. private static bool IsDelegate(Type type)
  276. {
  277. return typeof(Delegate).IsAssignableFrom(type);
  278. }
  279. private static bool IsTypeToDeepCopy(Type type)
  280. {
  281. return IsClassOtherThanString(type) || IsStructWhichNeedsDeepCopy(type);
  282. }
  283. private static bool IsClassOtherThanString(Type type)
  284. {
  285. return !type.IsValueType && type != typeof(string);
  286. }
  287. private static bool IsStructWhichNeedsDeepCopy(Type type)
  288. {
  289. if (!_isStructTypeToDeepCopyDictionary.TryGetValue(type, out var isStructTypeToDeepCopy))
  290. {
  291. lock (IsStructTypeToDeepCopyDictionaryLocker)
  292. {
  293. if (!_isStructTypeToDeepCopyDictionary.TryGetValue(type, out isStructTypeToDeepCopy))
  294. {
  295. isStructTypeToDeepCopy = IsStructWhichNeedsDeepCopy_NoDictionaryUsed(type);
  296. var newDictionary = _isStructTypeToDeepCopyDictionary.ToDictionary(pair => pair.Key, pair => pair.Value);
  297. newDictionary[type] = isStructTypeToDeepCopy;
  298. _isStructTypeToDeepCopyDictionary = newDictionary;
  299. }
  300. }
  301. }
  302. return isStructTypeToDeepCopy;
  303. }
  304. private static bool IsStructWhichNeedsDeepCopy_NoDictionaryUsed(Type type)
  305. {
  306. return IsStructOtherThanBasicValueTypes(type) && HasInItsHierarchyFieldsWithClasses(type);
  307. }
  308. private static bool IsStructOtherThanBasicValueTypes(Type type)
  309. {
  310. return type.IsValueType && !type.IsPrimitive && !type.IsEnum && type != typeof(decimal);
  311. }
  312. private static bool HasInItsHierarchyFieldsWithClasses(Type type, HashSet<Type> alreadyCheckedTypes = null)
  313. {
  314. alreadyCheckedTypes ??= new HashSet<Type>();
  315. alreadyCheckedTypes.Add(type);
  316. var allFields = GetAllFields(type);
  317. var allFieldTypes = allFields.Select(f => f.FieldType).Distinct().ToList();
  318. var hasFieldsWithClasses = allFieldTypes.Any(IsClassOtherThanString);
  319. if (hasFieldsWithClasses)
  320. {
  321. return true;
  322. }
  323. var notBasicStructsTypes = allFieldTypes.Where(IsStructOtherThanBasicValueTypes).ToList();
  324. var typesToCheck = notBasicStructsTypes.Where(t => !alreadyCheckedTypes.Contains(t)).ToList();
  325. return typesToCheck.Any(typeToCheck => HasInItsHierarchyFieldsWithClasses(typeToCheck, alreadyCheckedTypes));
  326. }
  327. public class ReferenceEqualityComparer : EqualityComparer<object>
  328. {
  329. public override bool Equals(object x, object y)
  330. {
  331. return ReferenceEquals(x, y);
  332. }
  333. public override int GetHashCode(object obj)
  334. {
  335. if (obj == null) return 0;
  336. return obj.GetHashCode();
  337. }
  338. }
  339. }
  340. }