ObjectExtensions.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using Masuit.Tools.Dynamics;
  8. using Masuit.Tools.Reflection;
  9. using Newtonsoft.Json.Linq;
  10. namespace Masuit.Tools
  11. {
  12. public static class ObjectExtensions
  13. {
  14. private static readonly MethodInfo CloneMethod = typeof(object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);
  15. public static bool IsPrimitive(this Type type)
  16. {
  17. if (type == typeof(string))
  18. {
  19. return true;
  20. }
  21. return type.IsValueType & type.IsPrimitive;
  22. }
  23. /// <summary>
  24. /// 判断类型是否是常见的简单类型
  25. /// </summary>
  26. /// <param name="type"></param>
  27. /// <returns></returns>
  28. public static bool IsSimpleType(this Type type)
  29. {
  30. //IsPrimitive 判断是否为基础类型。
  31. //基元类型为 Boolean、 Byte、 SByte、 Int16、 UInt16、 Int32、 UInt32、 Int64、 UInt64、 IntPtr、 UIntPtr、 Char、 Double 和 Single。
  32. var t = Nullable.GetUnderlyingType(type) ?? type;
  33. return t.IsPrimitive || t.IsEnum || t == typeof(decimal) || t == typeof(string) || t == typeof(Guid) || t == typeof(TimeSpan) || t == typeof(Uri);
  34. }
  35. /// <summary>
  36. /// 是否是常见类型的 数组形式 类型
  37. /// </summary>
  38. /// <param name="type"></param>
  39. /// <returns></returns>
  40. public static bool IsSimpleArrayType(this Type type)
  41. {
  42. return type.IsArray && Type.GetType(type.FullName!.Trim('[', ']')).IsSimpleType();
  43. }
  44. /// <summary>
  45. /// 是否是常见类型的 泛型形式 类型
  46. /// </summary>
  47. /// <param name="type"></param>
  48. /// <returns></returns>
  49. public static bool IsSimpleListType(this Type type)
  50. {
  51. type = Nullable.GetUnderlyingType(type) ?? type;
  52. return type.IsGenericType && type.GetGenericArguments().Length == 1 && type.GetGenericArguments().FirstOrDefault().IsSimpleType();
  53. }
  54. public static bool IsDefaultValue(this object value)
  55. {
  56. if (value == default)
  57. {
  58. return true;
  59. }
  60. return value switch
  61. {
  62. byte s => s == 0,
  63. sbyte s => s == 0,
  64. short s => s == 0,
  65. char s => s == 0,
  66. bool s => s,
  67. ushort s => s == 0,
  68. int s => s == 0,
  69. uint s => s == 0,
  70. long s => s == 0,
  71. ulong s => s == 0,
  72. decimal s => s == 0,
  73. float s => s == 0,
  74. double s => s == 0,
  75. Enum s => Equals(s, Enum.GetValues(value.GetType()).GetValue(0)),
  76. DateTime s => s == DateTime.MinValue,
  77. DateTimeOffset s => s == DateTimeOffset.MinValue,
  78. Guid g => g == Guid.Empty,
  79. _ => false
  80. };
  81. }
  82. public static object DeepClone(this object originalObject)
  83. {
  84. return InternalCopy(originalObject, new Dictionary<object, object>(new ReferenceEqualityComparer()));
  85. }
  86. public static T DeepClone<T>(this T original)
  87. {
  88. return (T)DeepClone((object)original);
  89. }
  90. private static object InternalCopy(object originalObject, IDictionary<object, object> visited)
  91. {
  92. if (originalObject == null)
  93. {
  94. return null;
  95. }
  96. var typeToReflect = originalObject.GetType();
  97. if (IsPrimitive(typeToReflect))
  98. {
  99. return originalObject;
  100. }
  101. if (visited.TryGetValue(originalObject, out var copy))
  102. {
  103. return copy;
  104. }
  105. if (typeof(Delegate).IsAssignableFrom(typeToReflect))
  106. {
  107. return null;
  108. }
  109. var cloneObject = CloneMethod.Invoke(originalObject, null);
  110. if (typeToReflect.IsArray)
  111. {
  112. var arrayType = typeToReflect.GetElementType();
  113. if (!IsPrimitive(arrayType))
  114. {
  115. Array clonedArray = (Array)cloneObject;
  116. clonedArray.ForEach((array, indices) => array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices));
  117. }
  118. }
  119. visited.Add(originalObject, cloneObject);
  120. CopyFields(originalObject, visited, cloneObject, typeToReflect);
  121. RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect);
  122. return cloneObject;
  123. }
  124. private static void RecursiveCopyBaseTypePrivateFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect)
  125. {
  126. if (typeToReflect.BaseType != null)
  127. {
  128. RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect.BaseType);
  129. CopyFields(originalObject, visited, cloneObject, typeToReflect.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info => info.IsPrivate);
  130. }
  131. }
  132. private static void CopyFields(object originalObject, IDictionary<object, object> visited, object cloneObject, IReflect typeToReflect, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func<FieldInfo, bool> filter = null)
  133. {
  134. foreach (FieldInfo fieldInfo in typeToReflect.GetFields(bindingFlags))
  135. {
  136. if (filter != null && !filter(fieldInfo))
  137. {
  138. continue;
  139. }
  140. if (IsPrimitive(fieldInfo.FieldType) || fieldInfo.IsInitOnly)
  141. {
  142. continue;
  143. }
  144. var originalFieldValue = fieldInfo.GetValue(originalObject);
  145. var clonedFieldValue = InternalCopy(originalFieldValue, visited);
  146. fieldInfo.SetValue(cloneObject, clonedFieldValue);
  147. }
  148. }
  149. /// <summary>
  150. /// 判断是否为null,null或0长度都返回true
  151. /// </summary>
  152. /// <typeparam name="T"></typeparam>
  153. /// <param name="value"></param>
  154. /// <returns></returns>
  155. public static bool IsNullOrEmpty<T>(this T value)
  156. where T : class
  157. {
  158. #region 1.对象级别
  159. //引用为null
  160. bool isObjectNull = value is null;
  161. if (isObjectNull)
  162. {
  163. return true;
  164. }
  165. //判断是否为集合
  166. var tempEnumerator = (value as IEnumerable)?.GetEnumerator();
  167. if (tempEnumerator == null) return false;//这里出去代表是对象 且 引用不为null.所以为false
  168. #endregion 1.对象级别
  169. #region 2.集合级别
  170. //到这里就代表是集合且引用不为空,判断长度
  171. //MoveNext方法返回tue代表集合中至少有一个数据,返回false就代表0长度
  172. bool isZeroLenth = tempEnumerator.MoveNext() == false;
  173. if (isZeroLenth) return true;
  174. return isZeroLenth;
  175. #endregion 2.集合级别
  176. }
  177. /// <summary>
  178. /// 转成非null
  179. /// </summary>
  180. /// <param name="s"></param>
  181. /// <param name="value">为空时的替换值</param>
  182. /// <returns></returns>
  183. public static T IfNull<T>(this T s, in T value)
  184. {
  185. return s ?? value;
  186. }
  187. /// <summary>
  188. /// 转换成json字符串
  189. /// </summary>
  190. /// <param name="obj"></param>
  191. /// <param name="setting"></param>
  192. /// <returns></returns>
  193. public static string ToJsonString(this object obj, JsonSerializerSettings setting = null)
  194. {
  195. if (obj == null) return string.Empty;
  196. return JsonConvert.SerializeObject(obj, setting);
  197. }
  198. /// <summary>
  199. /// json反序列化成对象
  200. /// </summary>
  201. public static T FromJson<T>(this string json, JsonSerializerSettings setting = null)
  202. {
  203. if (string.IsNullOrEmpty(json))
  204. {
  205. return default;
  206. }
  207. return JsonConvert.DeserializeObject<T>(json, setting);
  208. }
  209. /// <summary>
  210. /// 链式操作
  211. /// </summary>
  212. /// <typeparam name="T1"></typeparam>
  213. /// <typeparam name="T2"></typeparam>
  214. /// <param name="source"></param>
  215. /// <param name="action"></param>
  216. public static T2 Next<T1, T2>(this T1 source, Func<T1, T2> action)
  217. {
  218. return action(source);
  219. }
  220. /// <summary>
  221. /// 将对象转换成字典
  222. /// </summary>
  223. /// <param name="value"></param>
  224. public static Dictionary<string, object> ToDictionary(this object value)
  225. {
  226. var dictionary = new Dictionary<string, object>();
  227. if (value != null)
  228. {
  229. if (value is IDictionary dic)
  230. {
  231. foreach (DictionaryEntry e in dic)
  232. {
  233. dictionary.Add(e.Key.ToString(), e.Value);
  234. }
  235. return dictionary;
  236. }
  237. foreach (var property in value.GetType().GetProperties())
  238. {
  239. var obj = property.GetValue(value, null);
  240. dictionary.Add(property.Name, obj);
  241. }
  242. }
  243. return dictionary;
  244. }
  245. /// <summary>
  246. /// 将对象转换成字典
  247. /// </summary>
  248. /// <param name="value"></param>
  249. public static Dictionary<string, string> ToDictionary(this JObject value)
  250. {
  251. var dictionary = new Dictionary<string, string>();
  252. if (value != null)
  253. {
  254. var enumerator = value.GetEnumerator();
  255. while (enumerator.MoveNext())
  256. {
  257. var obj = enumerator.Current.Value ?? string.Empty;
  258. dictionary.Add(enumerator.Current.Key, obj + string.Empty);
  259. }
  260. }
  261. return dictionary;
  262. }
  263. /// <summary>
  264. /// 对象转换成动态类型
  265. /// </summary>
  266. /// <param name="obj"></param>
  267. /// <returns></returns>
  268. public static dynamic ToDynamic(this object obj)
  269. {
  270. return DynamicFactory.WithObject(obj);
  271. }
  272. /// <summary>
  273. /// 多个对象的属性值合并
  274. /// </summary>
  275. /// <typeparam name="T"></typeparam>
  276. /// <param name="a"></param>
  277. /// <param name="b"></param>
  278. /// <param name="others"></param>
  279. public static T Merge<T>(this T a, T b, params T[] others) where T : class
  280. {
  281. foreach (var item in new[] { b }.Concat(others))
  282. {
  283. var dic = item.ToDictionary();
  284. foreach (var p in dic.Where(p => a.GetProperty(p.Key).IsDefaultValue()))
  285. {
  286. a.SetProperty(p.Key, p.Value);
  287. }
  288. }
  289. return a;
  290. }
  291. /// <summary>
  292. /// 多个对象的属性值合并
  293. /// </summary>
  294. /// <typeparam name="T"></typeparam>
  295. public static T Merge<T>(this IEnumerable<T> objects) where T : class
  296. {
  297. var list = objects as List<T> ?? objects.ToList();
  298. if (list.Count == 0)
  299. {
  300. return null;
  301. }
  302. if (list.Count == 1)
  303. {
  304. return list[0];
  305. }
  306. foreach (var item in list.Skip(1))
  307. {
  308. var dic = item.ToDictionary();
  309. foreach (var p in dic.Where(p => list[0].GetProperty(p.Key).IsDefaultValue()))
  310. {
  311. list[0].SetProperty(p.Key, p.Value);
  312. }
  313. }
  314. return list[0];
  315. }
  316. }
  317. internal class ReferenceEqualityComparer : EqualityComparer<object>
  318. {
  319. public override bool Equals(object x, object y)
  320. {
  321. return ReferenceEquals(x, y);
  322. }
  323. public override int GetHashCode(object obj)
  324. {
  325. if (obj is null) return 0;
  326. return obj.GetHashCode();
  327. }
  328. }
  329. internal static class ArrayExtensions
  330. {
  331. public static void ForEach(this Array array, Action<Array, int[]> action)
  332. {
  333. if (array.LongLength == 0)
  334. {
  335. return;
  336. }
  337. ArrayTraverse walker = new ArrayTraverse(array);
  338. do action(array, walker.Position);
  339. while (walker.Step());
  340. }
  341. internal class ArrayTraverse
  342. {
  343. public int[] Position;
  344. private readonly int[] _maxLengths;
  345. public ArrayTraverse(Array array)
  346. {
  347. _maxLengths = new int[array.Rank];
  348. for (int i = 0; i < array.Rank; ++i)
  349. {
  350. _maxLengths[i] = array.GetLength(i) - 1;
  351. }
  352. Position = new int[array.Rank];
  353. }
  354. public bool Step()
  355. {
  356. for (int i = 0; i < Position.Length; ++i)
  357. {
  358. if (Position[i] < _maxLengths[i])
  359. {
  360. Position[i]++;
  361. for (int j = 0; j < i; j++)
  362. {
  363. Position[j] = 0;
  364. }
  365. return true;
  366. }
  367. }
  368. return false;
  369. }
  370. }
  371. }
  372. }