ObjectExtensions.cs 11 KB

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