ObjectExtensions.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections;
  4. namespace Masuit.Tools
  5. {
  6. public static class ObjectExtensions
  7. {
  8. public static bool IsPrimitive(this Type type)
  9. {
  10. if (type == typeof(string))
  11. {
  12. return true;
  13. }
  14. return type.IsValueType & type.IsPrimitive;
  15. }
  16. /// <summary>
  17. /// 判断是否为null,null或0长度都返回true
  18. /// </summary>
  19. /// <typeparam name="T"></typeparam>
  20. /// <param name="value"></param>
  21. /// <returns></returns>
  22. public static bool IsNullOrEmpty<T>(this T value)
  23. where T : class
  24. {
  25. #region 1.对象级别
  26. //引用为null
  27. bool isObjectNull = value is null;
  28. if (isObjectNull)
  29. {
  30. return true;
  31. }
  32. //判断是否为集合
  33. IEnumerator? tempEnumerator = (value as IEnumerable)?.GetEnumerator();
  34. if (tempEnumerator == null) return false;//这里出去代表是对象 且 引用不为null.所以为false
  35. #endregion 1.对象级别
  36. #region 2.集合级别
  37. //到这里就代表是集合且引用不为空,判断长度
  38. //MoveNext方法返回tue代表集合中至少有一个数据,返回false就代表0长度
  39. bool isZeroLenth = tempEnumerator.MoveNext() == false;
  40. if (isZeroLenth) return true;
  41. return isZeroLenth;
  42. #endregion 2.集合级别
  43. }
  44. /// <summary>
  45. /// 转换成json字符串
  46. /// </summary>
  47. /// <param name="obj"></param>
  48. /// <param name="setting"></param>
  49. /// <returns></returns>
  50. public static string ToJsonString(this object obj, JsonSerializerSettings setting = null)
  51. {
  52. if (obj == null) return string.Empty;
  53. return JsonConvert.SerializeObject(obj, setting);
  54. }
  55. /// <summary>
  56. /// 严格比较两个对象是否是同一对象(判断引用)
  57. /// </summary>
  58. /// <param name="this">自己</param>
  59. /// <param name="o">需要比较的对象</param>
  60. /// <returns>是否同一对象</returns>
  61. public new static bool ReferenceEquals(this object @this, object o)
  62. {
  63. return object.ReferenceEquals(@this, o);
  64. }
  65. }
  66. }