You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Inspector.cs 2.7 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections;
  2. using System.Linq;
  3. using System.Reflection;
  4. using System.Text;
  5. namespace Idn
  6. {
  7. public static class Inspector
  8. {
  9. public static string Inspect(object value)
  10. {
  11. var builder = new StringBuilder();
  12. if (value != null)
  13. {
  14. var type = value.GetType().GetTypeInfo();
  15. builder.AppendLine($"[{type.Namespace}.{type.Name}]");
  16. builder.AppendLine($"{InspectProperty(value)}");
  17. if (value is IEnumerable)
  18. {
  19. var items = (value as IEnumerable).Cast<object>().ToArray();
  20. if (items.Length > 0)
  21. {
  22. builder.AppendLine();
  23. foreach (var item in items)
  24. builder.AppendLine($"- {InspectProperty(item)}");
  25. }
  26. }
  27. else
  28. {
  29. var groups = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
  30. .Where(x => x.GetIndexParameters().Length == 0)
  31. .GroupBy(x => x.Name)
  32. .OrderBy(x => x.Key)
  33. .ToArray();
  34. if (groups.Length > 0)
  35. {
  36. builder.AppendLine();
  37. int pad = groups.Max(x => x.Key.Length) + 1;
  38. foreach (var group in groups)
  39. builder.AppendLine($"{group.Key.PadRight(pad, ' ')}{InspectProperty(group.First().GetValue(value))}");
  40. }
  41. }
  42. }
  43. else
  44. builder.AppendLine("null");
  45. return builder.ToString();
  46. }
  47. private static string InspectProperty(object obj)
  48. {
  49. if (obj == null)
  50. return "null";
  51. var type = obj.GetType();
  52. var debuggerDisplay = type.GetProperty("DebuggerDisplay", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  53. if (debuggerDisplay != null)
  54. return debuggerDisplay.GetValue(obj).ToString();
  55. var toString = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
  56. .Where(x => x.Name == "ToString" && x.DeclaringType != typeof(object))
  57. .FirstOrDefault();
  58. if (toString != null)
  59. return obj.ToString();
  60. var count = type.GetProperty("Count", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  61. if (count != null)
  62. return $"[{count.GetValue(obj)} Items]";
  63. return obj.ToString();
  64. }
  65. }
  66. }