ObjectExtensions.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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
  133. ? InternalJsonCopy(originalObject)
  134. : InternalCopy(originalObject, new Dictionary<object, object>(new ReferenceEqualityComparer()));
  135. }
  136. /// <summary>
  137. /// 深克隆
  138. /// </summary>
  139. /// <typeparam name="T"></typeparam>
  140. /// <param name="original"></param>
  141. /// <param name="useJson">使用json方式</param>
  142. /// <returns></returns>
  143. public static T DeepClone<T>(this T original, bool useJson = false)
  144. {
  145. return useJson ? InternalJsonCopy(original) : (T)InternalCopy(original, new Dictionary<object, object>(new ReferenceEqualityComparer()));
  146. }
  147. #if NETSTANDARD2_1_OR_GREATER
  148. private static T InternalJsonCopy<T>(T obj)
  149. {
  150. using var stream = new PooledMemoryStream();
  151. using var writer = new Utf8JsonWriter(stream);
  152. JsonSerializer.Serialize(writer, obj);
  153. writer.Flush();
  154. var reader = new Utf8JsonReader(stream.ToArray());
  155. return JsonSerializer.Deserialize<T>(ref reader);
  156. }
  157. #else
  158. private static T InternalJsonCopy<T>(T obj)
  159. {
  160. return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(obj));
  161. }
  162. #endif
  163. private static object InternalCopy(object originalObject, IDictionary<object, object> visited)
  164. {
  165. if (originalObject == null)
  166. {
  167. return null;
  168. }
  169. var typeToReflect = originalObject.GetType();
  170. if (IsPrimitive(typeToReflect))
  171. {
  172. return originalObject;
  173. }
  174. if (visited.TryGetValue(originalObject, out var copy))
  175. {
  176. return copy;
  177. }
  178. if (typeof(Delegate).IsAssignableFrom(typeToReflect))
  179. {
  180. return null;
  181. }
  182. var cloneObject = CloneMethod.Invoke(originalObject, null);
  183. if (typeToReflect.IsArray)
  184. {
  185. var arrayType = typeToReflect.GetElementType();
  186. if (!IsPrimitive(arrayType))
  187. {
  188. Array clonedArray = (Array)cloneObject;
  189. clonedArray.ForEach((array, indices) => array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices));
  190. }
  191. }
  192. visited.Add(originalObject, cloneObject);
  193. CopyFields(originalObject, visited, cloneObject, typeToReflect);
  194. RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect);
  195. return cloneObject;
  196. }
  197. private static void RecursiveCopyBaseTypePrivateFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect)
  198. {
  199. if (typeToReflect.BaseType != null)
  200. {
  201. RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect.BaseType);
  202. CopyFields(originalObject, visited, cloneObject, typeToReflect.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info => info.IsPrivate);
  203. }
  204. }
  205. 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)
  206. {
  207. foreach (FieldInfo fieldInfo in typeToReflect.GetFields(bindingFlags))
  208. {
  209. if (filter != null && !filter(fieldInfo))
  210. {
  211. continue;
  212. }
  213. if (IsPrimitive(fieldInfo.FieldType) || fieldInfo.IsInitOnly)
  214. {
  215. continue;
  216. }
  217. var originalFieldValue = fieldInfo.GetValue(originalObject);
  218. var clonedFieldValue = InternalCopy(originalFieldValue, visited);
  219. fieldInfo.SetValue(cloneObject, clonedFieldValue);
  220. }
  221. }
  222. /// <summary>
  223. /// 判断是否为null,null或0长度都返回true
  224. /// </summary>
  225. /// <typeparam name="T"></typeparam>
  226. /// <param name="value"></param>
  227. /// <returns></returns>
  228. public static bool IsNullOrEmpty<T>(this T value)
  229. where T : class
  230. {
  231. return value switch
  232. {
  233. null => true,
  234. string s => string.IsNullOrWhiteSpace(s),
  235. IEnumerable list => !list.GetEnumerator().MoveNext(),
  236. _ => false
  237. };
  238. }
  239. /// <summary>
  240. /// 转成非null
  241. /// </summary>
  242. /// <param name="s"></param>
  243. /// <param name="value">为空时的替换值</param>
  244. /// <returns></returns>
  245. public static T IfNull<T>(this T s, in T value)
  246. {
  247. return s ?? value;
  248. }
  249. /// <summary>
  250. /// 转换成json字符串
  251. /// </summary>
  252. /// <param name="obj"></param>
  253. /// <param name="setting"></param>
  254. /// <returns></returns>
  255. public static string ToJsonString(this object obj, JsonSerializerSettings setting = null)
  256. {
  257. if (obj == null) return string.Empty;
  258. return JsonConvert.SerializeObject(obj, setting);
  259. }
  260. /// <summary>
  261. /// json反序列化成对象
  262. /// </summary>
  263. public static T FromJson<T>(this string json, JsonSerializerSettings setting = null)
  264. {
  265. return string.IsNullOrEmpty(json) ? default : JsonConvert.DeserializeObject<T>(json, setting);
  266. }
  267. #region System.Text.Json
  268. #if NET5_0_OR_GREATER
  269. /// <summary>
  270. /// 转换成json字符串
  271. /// </summary>
  272. /// <param name="obj"></param>
  273. /// <param name="setting"></param>
  274. /// <returns></returns>
  275. public static string ToJson(this object obj, JsonSerializerOptions setting = null)
  276. {
  277. if (obj == null) return string.Empty;
  278. setting ??= DefaultJsonSerializerOptions;
  279. return JsonSerializer.Serialize(obj,setting);
  280. }
  281. /// <summary>
  282. /// 转换成json字符串并忽略Null值
  283. /// </summary>
  284. /// <param name="obj"></param>
  285. /// <param name="setting"></param>
  286. /// <returns></returns>
  287. public static string ToJsonIgnoreNull(this object obj)
  288. {
  289. if (obj == null) return string.Empty;
  290. return JsonSerializer.Serialize(obj,IgnoreNullJsonSerializerOptions);
  291. }
  292. /// <summary>
  293. /// 反序列化
  294. /// </summary>
  295. /// <param name="json"></param>
  296. /// <param name="settings"></param>
  297. /// <returns></returns>
  298. public static T ToObject<T>(this string json, JsonSerializerOptions settings = null)
  299. {
  300. return string.IsNullOrEmpty(json) ? default : JsonSerializer.Deserialize<T>(json, settings);
  301. }
  302. #endif
  303. #endregion
  304. /// <summary>
  305. /// 链式操作
  306. /// </summary>
  307. /// <typeparam name="T1"></typeparam>
  308. /// <typeparam name="T2"></typeparam>
  309. /// <param name="source"></param>
  310. /// <param name="action"></param>
  311. public static T2 Next<T1, T2>(this T1 source, Func<T1, T2> action)
  312. {
  313. return action(source);
  314. }
  315. /// <summary>
  316. /// 将对象转换成字典
  317. /// </summary>
  318. /// <param name="value"></param>
  319. public static Dictionary<string, object> ToDictionary(this object value)
  320. {
  321. var dictionary = new Dictionary<string, object>();
  322. if (value != null)
  323. {
  324. if (value is IDictionary dic)
  325. {
  326. foreach (DictionaryEntry e in dic)
  327. {
  328. dictionary.Add(e.Key.ToString(), e.Value);
  329. }
  330. return dictionary;
  331. }
  332. foreach (var property in value.GetType().GetProperties())
  333. {
  334. var obj = property.GetValue(value, null);
  335. dictionary.Add(property.Name, obj);
  336. }
  337. }
  338. return dictionary;
  339. }
  340. /// <summary>
  341. /// 将对象转换成字典
  342. /// </summary>
  343. /// <param name="value"></param>
  344. public static Dictionary<string, string> ToDictionary(this JObject value)
  345. {
  346. var dictionary = new Dictionary<string, string>();
  347. if (value != null)
  348. {
  349. using var enumerator = value.GetEnumerator();
  350. while (enumerator.MoveNext())
  351. {
  352. var obj = enumerator.Current.Value ?? string.Empty;
  353. dictionary.Add(enumerator.Current.Key, obj + string.Empty);
  354. }
  355. }
  356. return dictionary;
  357. }
  358. /// <summary>
  359. /// 对象转换成动态类型
  360. /// </summary>
  361. /// <param name="obj"></param>
  362. /// <returns></returns>
  363. public static dynamic ToDynamic(this object obj)
  364. {
  365. return DynamicFactory.WithObject(obj);
  366. }
  367. /// <summary>
  368. /// 多个对象的属性值合并
  369. /// </summary>
  370. /// <typeparam name="T"></typeparam>
  371. /// <param name="a"></param>
  372. /// <param name="b"></param>
  373. /// <param name="others"></param>
  374. public static T Merge<T>(this T a, T b, params T[] others) where T : class
  375. {
  376. foreach (var item in new[] { b }.Concat(others))
  377. {
  378. var dic = item.ToDictionary();
  379. foreach (var p in dic.Where(p => a.GetProperty(p.Key).IsDefaultValue()))
  380. {
  381. a.SetProperty(p.Key, p.Value);
  382. }
  383. }
  384. return a;
  385. }
  386. /// <summary>
  387. /// 多个对象的属性值合并
  388. /// </summary>
  389. /// <typeparam name="T"></typeparam>
  390. public static T Merge<T>(this IEnumerable<T> objects) where T : class
  391. {
  392. var list = objects as List<T> ?? objects.ToList();
  393. switch (list.Count)
  394. {
  395. case 0:
  396. return null;
  397. case 1:
  398. return list[0];
  399. }
  400. foreach (var item in list.Skip(1))
  401. {
  402. var dic = item.ToDictionary();
  403. foreach (var p in dic.Where(p => list[0].GetProperty(p.Key).IsDefaultValue()))
  404. {
  405. list[0].SetProperty(p.Key, p.Value);
  406. }
  407. }
  408. return list[0];
  409. }
  410. }
  411. internal class ReferenceEqualityComparer : EqualityComparer<object>
  412. {
  413. public override bool Equals(object x, object y)
  414. {
  415. return ReferenceEquals(x, y);
  416. }
  417. public override int GetHashCode(object obj)
  418. {
  419. return obj is null ? 0 : obj.GetHashCode();
  420. }
  421. }
  422. internal static class ArrayExtensions
  423. {
  424. public static void ForEach(this Array array, Action<Array, int[]> action)
  425. {
  426. if (array.LongLength == 0)
  427. {
  428. return;
  429. }
  430. ArrayTraverse walker = new ArrayTraverse(array);
  431. do action(array, walker.Position);
  432. while (walker.Step());
  433. }
  434. internal class ArrayTraverse
  435. {
  436. public int[] Position;
  437. private readonly int[] _maxLengths;
  438. public ArrayTraverse(Array array)
  439. {
  440. _maxLengths = new int[array.Rank];
  441. for (int i = 0; i < array.Rank; ++i)
  442. {
  443. _maxLengths[i] = array.GetLength(i) - 1;
  444. }
  445. Position = new int[array.Rank];
  446. }
  447. public bool Step()
  448. {
  449. for (int i = 0; i < Position.Length; ++i)
  450. {
  451. if (Position[i] < _maxLengths[i])
  452. {
  453. Position[i]++;
  454. for (int j = 0; j < i; j++)
  455. {
  456. Position[j] = 0;
  457. }
  458. return true;
  459. }
  460. }
  461. return false;
  462. }
  463. }
  464. }