1
1

ObjectExtensions.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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) || fieldInfo.IsInitOnly)
  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="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. if (type.IsNumeric())
  160. {
  161. return (double)value == 0;
  162. }
  163. return false;
  164. }
  165. /// <summary>
  166. /// 链式操作
  167. /// </summary>
  168. /// <typeparam name="T1"></typeparam>
  169. /// <typeparam name="T2"></typeparam>
  170. /// <param name="source"></param>
  171. /// <param name="action"></param>
  172. /// <returns></returns>
  173. public static T2 Next<T1, T2>(this T1 source, Func<T1, T2> action)
  174. {
  175. return action(source);
  176. }
  177. }
  178. internal class ReferenceEqualityComparer : EqualityComparer<object>
  179. {
  180. public override bool Equals(object x, object y)
  181. {
  182. return ReferenceEquals(x, y);
  183. }
  184. public override int GetHashCode(object obj)
  185. {
  186. if (obj is null) return 0;
  187. return obj.GetHashCode();
  188. }
  189. }
  190. internal static class ArrayExtensions
  191. {
  192. public static void ForEach(this Array array, Action<Array, int[]> action)
  193. {
  194. if (array.LongLength == 0)
  195. {
  196. return;
  197. }
  198. ArrayTraverse walker = new ArrayTraverse(array);
  199. do action(array, walker.Position);
  200. while (walker.Step());
  201. }
  202. internal class ArrayTraverse
  203. {
  204. public int[] Position;
  205. private readonly int[] _maxLengths;
  206. public ArrayTraverse(Array array)
  207. {
  208. _maxLengths = new int[array.Rank];
  209. for (int i = 0; i < array.Rank; ++i)
  210. {
  211. _maxLengths[i] = array.GetLength(i) - 1;
  212. }
  213. Position = new int[array.Rank];
  214. }
  215. public bool Step()
  216. {
  217. for (int i = 0; i < Position.Length; ++i)
  218. {
  219. if (Position[i] < _maxLengths[i])
  220. {
  221. Position[i]++;
  222. for (int j = 0; j < i; j++)
  223. {
  224. Position[j] = 0;
  225. }
  226. return true;
  227. }
  228. }
  229. return false;
  230. }
  231. }
  232. }
  233. }