ObjectExtension.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System.Reflection;
  2. using System.Text.RegularExpressions;
  3. namespace Alchemy.Core.Extensions
  4. {
  5. public static class ObjectExtension
  6. {
  7. /// <summary>
  8. /// 判断对象是否为null
  9. /// </summary>
  10. /// <param name="obj"></param>
  11. /// <returns></returns>
  12. public static bool IsNull(this object? obj)
  13. {
  14. return obj is null;
  15. }
  16. public static bool IsNotNull(this object? obj)
  17. {
  18. return !obj.IsNull();
  19. }
  20. public static bool SetPropValue(this object? obj, string strPropName, object value)
  21. {
  22. bool result = false;
  23. if (obj.IsNull())
  24. return result;
  25. Type type = obj.GetType();
  26. PropertyInfo propertyInfo = type.GetProperty(strPropName);
  27. if (propertyInfo != null && propertyInfo.CanWrite)
  28. {
  29. propertyInfo.SetValue(obj, value, null);
  30. result = true;
  31. }
  32. return result;
  33. }
  34. /// <summary>
  35. /// 下划线转驼峰的转换
  36. /// </summary>
  37. /// <param name="obj"></param>
  38. /// <returns></returns>
  39. /// <exception cref="ArgumentNullException"></exception>
  40. public static Dictionary<string, object> ToDictionary(this object? obj)
  41. {
  42. if (obj == null)
  43. throw new ArgumentNullException(nameof(obj));
  44. var dictionary = new Dictionary<string, object>();
  45. foreach (var property in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
  46. {
  47. var key = ToCamelCase(property.Name);
  48. var value = property.GetValue(obj, null);
  49. dictionary[key] = value;
  50. }
  51. return dictionary;
  52. }
  53. private static string ToCamelCase(string input)
  54. {
  55. return Regex.Replace(input, "([a-z])_([a-z])", m => m.Groups[1].Value + m.Groups[2].Value.ToUpperInvariant());
  56. }
  57. }
  58. }