ObjectExt.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System.Collections;
  2. using Quadarax.Foundation.Core.Reflection.Extensions;
  3. namespace Quadarax.Foundation.Core.Object.Extensions
  4. {
  5. public static class ObjectExt
  6. {
  7. public static IDictionary<string, object?> GetAllPropertyValues(this object? obj,string? indentPrefix = null)
  8. {
  9. var props = new Dictionary<string, object?>();
  10. if (obj == null)
  11. return props;
  12. if (string.IsNullOrEmpty(indentPrefix))
  13. indentPrefix = string.Empty;
  14. var type = obj.GetType();
  15. var propList = type.GetAllProperties();
  16. foreach (var prop in propList)
  17. {
  18. var val = prop.GetValue(obj, new object[] { });
  19. if (val is IEnumerable enumerable)
  20. {
  21. var cnt = 0;
  22. foreach (var item in enumerable)
  23. {
  24. var itemProps = item.GetAllPropertyValues(prop.Name + $"[{cnt}].");
  25. foreach (var ip in itemProps)
  26. props.Add(ip.Key, ip.Value);
  27. cnt++;
  28. }
  29. }
  30. else
  31. props.Add(indentPrefix + prop.Name, val);
  32. }
  33. return props;
  34. }
  35. }
  36. }