ObjectExtensions.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. /// 转成非null
  116. /// </summary>
  117. /// <param name="s"></param>
  118. /// <param name="value">为空时的替换值</param>
  119. /// <returns></returns>
  120. public static T IfNull<T>(this T s, T value)
  121. {
  122. return s ?? value;
  123. }
  124. /// <summary>
  125. /// 转换成json字符串
  126. /// </summary>
  127. /// <param name="obj"></param>
  128. /// <param name="setting"></param>
  129. /// <returns></returns>
  130. public static string ToJsonString(this object obj, JsonSerializerSettings setting = null)
  131. {
  132. if (obj == null) return string.Empty;
  133. return JsonConvert.SerializeObject(obj, setting);
  134. }
  135. /// <summary>
  136. /// 严格比较两个对象是否是同一对象(判断引用)
  137. /// </summary>
  138. /// <param name="this">自己</param>
  139. /// <param name="o">需要比较的对象</param>
  140. /// <returns>是否同一对象</returns>
  141. public new static bool ReferenceEquals(this object @this, object o)
  142. {
  143. return object.ReferenceEquals(@this, o);
  144. }
  145. /// <summary>
  146. /// 是否是默认值
  147. /// </summary>
  148. /// <param name="value"></param>
  149. /// <returns></returns>
  150. public static bool IsDefaultValue(this object value)
  151. {
  152. if (value == null)
  153. {
  154. return true;
  155. }
  156. var type = value.GetType();
  157. if (type == typeof(bool))
  158. {
  159. return (bool)value == false;
  160. }
  161. if (type.IsEnum)
  162. {
  163. return (int)value == 0;
  164. }
  165. if (type == typeof(DateTime))
  166. {
  167. return (DateTime)value == default;
  168. }
  169. return double.Parse(value.ToString()) == 0;
  170. }
  171. /// <summary>
  172. /// 链式操作
  173. /// </summary>
  174. /// <typeparam name="T1"></typeparam>
  175. /// <typeparam name="T2"></typeparam>
  176. /// <param name="source"></param>
  177. /// <param name="action"></param>
  178. /// <returns></returns>
  179. public static T2 Next<T1, T2>(this T1 source, Func<T1, T2> action)
  180. {
  181. return action(source);
  182. }
  183. }
  184. internal class ReferenceEqualityComparer : EqualityComparer<object>
  185. {
  186. public override bool Equals(object x, object y)
  187. {
  188. return ReferenceEquals(x, y);
  189. }
  190. public override int GetHashCode(object obj)
  191. {
  192. if (obj is null) return 0;
  193. return obj.GetHashCode();
  194. }
  195. }
  196. internal static class ArrayExtensions
  197. {
  198. public static void ForEach(this Array array, Action<Array, int[]> action)
  199. {
  200. if (array.LongLength == 0)
  201. {
  202. return;
  203. }
  204. ArrayTraverse walker = new ArrayTraverse(array);
  205. do action(array, walker.Position);
  206. while (walker.Step());
  207. }
  208. internal class ArrayTraverse
  209. {
  210. public int[] Position;
  211. private readonly int[] _maxLengths;
  212. public ArrayTraverse(Array array)
  213. {
  214. _maxLengths = new int[array.Rank];
  215. for (int i = 0; i < array.Rank; ++i)
  216. {
  217. _maxLengths[i] = array.GetLength(i) - 1;
  218. }
  219. Position = new int[array.Rank];
  220. }
  221. public bool Step()
  222. {
  223. for (int i = 0; i < Position.Length; ++i)
  224. {
  225. if (Position[i] < _maxLengths[i])
  226. {
  227. Position[i]++;
  228. for (int j = 0; j < i; j++)
  229. {
  230. Position[j] = 0;
  231. }
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. }
  238. }
  239. }