ObjectExtensions.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Reflection;
  6. namespace Masuit.Tools
  7. {
  8. public static class ObjectExtensions
  9. {
  10. private static readonly MethodInfo CloneMethod = typeof(object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);
  11. public static bool IsPrimitive(this Type type)
  12. {
  13. if (type == typeof(string))
  14. {
  15. return true;
  16. }
  17. return type.IsValueType & type.IsPrimitive;
  18. }
  19. public static object DeepClone(this object originalObject)
  20. {
  21. return InternalCopy(originalObject, new Dictionary<object, object>(new ReferenceEqualityComparer()));
  22. }
  23. public static T DeepClone<T>(this T original)
  24. {
  25. return (T)DeepClone((object)original);
  26. }
  27. private static object InternalCopy(object originalObject, IDictionary<object, object> visited)
  28. {
  29. if (originalObject == null)
  30. {
  31. return null;
  32. }
  33. var typeToReflect = originalObject.GetType();
  34. if (IsPrimitive(typeToReflect))
  35. {
  36. return originalObject;
  37. }
  38. if (visited.ContainsKey(originalObject))
  39. {
  40. return visited[originalObject];
  41. }
  42. if (typeof(Delegate).IsAssignableFrom(typeToReflect))
  43. {
  44. return null;
  45. }
  46. var cloneObject = CloneMethod.Invoke(originalObject, null);
  47. if (typeToReflect.IsArray)
  48. {
  49. var arrayType = typeToReflect.GetElementType();
  50. if (!IsPrimitive(arrayType))
  51. {
  52. Array clonedArray = (Array)cloneObject;
  53. clonedArray.ForEach((array, indices) => array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices));
  54. }
  55. }
  56. visited.Add(originalObject, cloneObject);
  57. CopyFields(originalObject, visited, cloneObject, typeToReflect);
  58. RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect);
  59. return cloneObject;
  60. }
  61. private static void RecursiveCopyBaseTypePrivateFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect)
  62. {
  63. if (typeToReflect.BaseType != null)
  64. {
  65. RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect.BaseType);
  66. CopyFields(originalObject, visited, cloneObject, typeToReflect.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info => info.IsPrivate);
  67. }
  68. }
  69. private static void CopyFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func<FieldInfo, bool> filter = null)
  70. {
  71. foreach (FieldInfo fieldInfo in typeToReflect.GetFields(bindingFlags))
  72. {
  73. if (filter != null && !filter(fieldInfo))
  74. {
  75. continue;
  76. }
  77. if (IsPrimitive(fieldInfo.FieldType))
  78. {
  79. continue;
  80. }
  81. var originalFieldValue = fieldInfo.GetValue(originalObject);
  82. var clonedFieldValue = InternalCopy(originalFieldValue, visited);
  83. fieldInfo.SetValue(cloneObject, clonedFieldValue);
  84. }
  85. }
  86. /// <summary>
  87. /// 判断是否为null,null或0长度都返回true
  88. /// </summary>
  89. /// <typeparam name="T"></typeparam>
  90. /// <param name="value"></param>
  91. /// <returns></returns>
  92. public static bool IsNullOrEmpty<T>(this T value)
  93. where T : class
  94. {
  95. #region 1.对象级别
  96. //引用为null
  97. bool isObjectNull = value is null;
  98. if (isObjectNull)
  99. {
  100. return true;
  101. }
  102. //判断是否为集合
  103. var tempEnumerator = (value as IEnumerable)?.GetEnumerator();
  104. if (tempEnumerator == null) return false;//这里出去代表是对象 且 引用不为null.所以为false
  105. #endregion 1.对象级别
  106. #region 2.集合级别
  107. //到这里就代表是集合且引用不为空,判断长度
  108. //MoveNext方法返回tue代表集合中至少有一个数据,返回false就代表0长度
  109. bool isZeroLenth = tempEnumerator.MoveNext() == false;
  110. if (isZeroLenth) return true;
  111. return isZeroLenth;
  112. #endregion 2.集合级别
  113. }
  114. /// <summary>
  115. /// 转换成json字符串
  116. /// </summary>
  117. /// <param name="obj"></param>
  118. /// <param name="setting"></param>
  119. /// <returns></returns>
  120. public static string ToJsonString(this object obj, JsonSerializerSettings setting = null)
  121. {
  122. if (obj == null) return string.Empty;
  123. return JsonConvert.SerializeObject(obj, setting);
  124. }
  125. /// <summary>
  126. /// 严格比较两个对象是否是同一对象(判断引用)
  127. /// </summary>
  128. /// <param name="this">自己</param>
  129. /// <param name="o">需要比较的对象</param>
  130. /// <returns>是否同一对象</returns>
  131. public new static bool ReferenceEquals(this object @this, object o)
  132. {
  133. return object.ReferenceEquals(@this, o);
  134. }
  135. /// <summary>
  136. /// 是否是默认值
  137. /// </summary>
  138. /// <param name="value"></param>
  139. /// <returns></returns>
  140. public static bool IsDefaultValue(this object value)
  141. {
  142. if (value == null)
  143. {
  144. return true;
  145. }
  146. var type = value.GetType();
  147. if (type == typeof(bool))
  148. {
  149. return (bool)value == false;
  150. }
  151. if (type.IsEnum)
  152. {
  153. return (int)value == 0;
  154. }
  155. if (type == typeof(DateTime))
  156. {
  157. return (DateTime)value == default;
  158. }
  159. return double.Parse(value.ToString()) == 0;
  160. }
  161. /// <summary>
  162. /// 链式操作
  163. /// </summary>
  164. /// <typeparam name="T1"></typeparam>
  165. /// <typeparam name="T2"></typeparam>
  166. /// <param name="source"></param>
  167. /// <param name="action"></param>
  168. /// <returns></returns>
  169. public static T2 Next<T1, T2>(this T1 source, Func<T1, T2> action)
  170. {
  171. return action(source);
  172. }
  173. }
  174. class ReferenceEqualityComparer : EqualityComparer<object>
  175. {
  176. public override bool Equals(object x, object y)
  177. {
  178. return ReferenceEquals(x, y);
  179. }
  180. public override int GetHashCode(object obj)
  181. {
  182. if (obj is null) return 0;
  183. return obj.GetHashCode();
  184. }
  185. }
  186. static class ArrayExtensions
  187. {
  188. public static void ForEach(this Array array, Action<Array, int[]> action)
  189. {
  190. if (array.LongLength == 0)
  191. {
  192. return;
  193. }
  194. ArrayTraverse walker = new ArrayTraverse(array);
  195. do action(array, walker.Position);
  196. while (walker.Step());
  197. }
  198. internal class ArrayTraverse
  199. {
  200. public int[] Position;
  201. private readonly int[] _maxLengths;
  202. public ArrayTraverse(Array array)
  203. {
  204. _maxLengths = new int[array.Rank];
  205. for (int i = 0; i < array.Rank; ++i)
  206. {
  207. _maxLengths[i] = array.GetLength(i) - 1;
  208. }
  209. Position = new int[array.Rank];
  210. }
  211. public bool Step()
  212. {
  213. for (int i = 0; i < Position.Length; ++i)
  214. {
  215. if (Position[i] < _maxLengths[i])
  216. {
  217. Position[i]++;
  218. for (int j = 0; j < i; j++)
  219. {
  220. Position[j] = 0;
  221. }
  222. return true;
  223. }
  224. }
  225. return false;
  226. }
  227. }
  228. }
  229. }