ExtendUtil.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Linq;
  3. using System.Text.Json;
  4. using System.Reflection;
  5. using System.ComponentModel;
  6. using System.Collections.Generic;
  7. using System.Collections.ObjectModel;
  8. using System.Text.Encodings.Web;
  9. namespace SHJX.Service.Common.Extend
  10. {
  11. /// <summary>
  12. /// 扩展
  13. /// </summary>
  14. public static class ExtendUtil
  15. {
  16. #region 包含反转
  17. /// <summary>
  18. /// 包含反转
  19. /// </summary>
  20. /// <param name="value"></param>
  21. /// <param name="values"></param>
  22. /// <returns></returns>
  23. public static bool In(this object value, params object[] values) =>
  24. values.Contains(value);
  25. public static bool In<T>(this T value, params T[] values) where T : class =>
  26. values.Contains(value);
  27. #endregion
  28. /// <summary>
  29. /// 根据值得到中文备注
  30. /// </summary>
  31. /// <param name="t"></param>
  32. /// <param name="value"></param>
  33. /// <returns></returns>
  34. public static string GetEnumDesc<T>(this Enum value) where T : Enum
  35. {
  36. Type t = typeof(T);
  37. FieldInfo[] fields = t.GetFields();
  38. for (int i = 1, count = fields.Length; i < count; i++)
  39. {
  40. if (Enum.Parse(t, fields[i].Name) != value) continue;
  41. var enumAttributes = (DescriptionAttribute[])fields[i].GetCustomAttributes(typeof(DescriptionAttribute), false);
  42. if (enumAttributes.Length > 0)
  43. {
  44. return enumAttributes[0].Description;
  45. }
  46. }
  47. return string.Empty;
  48. }
  49. public static string Uuid => Guid.NewGuid().ToString("N").ToUpper();
  50. public static Collection<T> AddRange<T>(this Collection<T> collection, IEnumerable<T> items)
  51. {
  52. if (collection == null)
  53. throw new ArgumentNullException(nameof (collection));
  54. if (items == null)
  55. throw new ArgumentNullException(nameof (items));
  56. foreach (T obj in items)
  57. collection.Add(obj);
  58. return collection;
  59. }
  60. #region 深克隆
  61. /// <summary>
  62. /// Clones the specified list.
  63. /// </summary>
  64. /// <typeparam name="T"></typeparam>
  65. /// <param name="List">The list.</param>
  66. /// <returns>List{``0}.</returns>
  67. public static List<T> Clone<T>(this List<T> list) where T : class
  68. {
  69. var deserializeSettings = JsonSerializer.Serialize(list, new JsonSerializerOptions
  70. {
  71. Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
  72. });
  73. return JsonSerializer.Deserialize<List<T>>(deserializeSettings);
  74. }
  75. #endregion
  76. }
  77. }