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