ObjectExtensions.cs 15 KB

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