ObjectExt.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using Quadarax.Foundation.Core.Reflection.Extensions;
  6. namespace Quadarax.Foundation.Core.Object.Extensions
  7. {
  8. public static class ObjectExt
  9. {
  10. public static IDictionary<string, object> GetAllPropertyValues(this object obj,string indentPrefix = null)
  11. {
  12. var props = new Dictionary<string, object>();
  13. if (obj == null)
  14. return props;
  15. if (string.IsNullOrEmpty(indentPrefix))
  16. indentPrefix = string.Empty;
  17. var type = obj.GetType();
  18. var propList = type.GetAllProperties();
  19. foreach (var prop in propList)
  20. {
  21. var val = prop.GetValue(obj, new object[] { });
  22. if (val is IEnumerable enumerable)
  23. {
  24. var cnt = 0;
  25. foreach (var item in enumerable)
  26. {
  27. var itemProps = item.GetAllPropertyValues(prop.Name + $"[{cnt}].");
  28. foreach (var ip in itemProps)
  29. props.Add(ip.Key, ip.Value);
  30. cnt++;
  31. }
  32. }
  33. else
  34. props.Add(indentPrefix + prop.Name, val);
  35. }
  36. return props;
  37. }
  38. public static void SetAllPropertyValues(this object obj,IDictionary<string, object> values,string indentPrefix = null, bool silent = false)
  39. {
  40. if (obj == null)
  41. return;
  42. if (values == null || values.Count == 0)
  43. return;
  44. if (string.IsNullOrEmpty(indentPrefix))
  45. indentPrefix = string.Empty;
  46. var type = obj.GetType();
  47. var propList = type.GetAllProperties();
  48. foreach (var val in values)
  49. {
  50. var propName = val.Key;
  51. var prop = propList.FirstOrDefault(x => x.Name == val.Key);
  52. if (prop == null)
  53. if (!silent)
  54. throw new InvalidOperationException(
  55. $"Cannot locate property '{val.Key}' in class '{obj.GetType().Name}'.");
  56. prop.SetValue(obj,val);
  57. }
  58. }
  59. }
  60. }