ObjectExtensions.cs 13 KB

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