ObjectExtensions.cs 13 KB

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