Dumper.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using System;
  2. using System.Collections;
  3. using System.Reflection;
  4. using System.Text;
  5. using Google.Protobuf;
  6. using UnityEngine;
  7. namespace ET
  8. {
  9. public static class Dumper
  10. {
  11. private static readonly StringBuilder _text = new StringBuilder("", 1024);
  12. private static void AppendIndent(int num)
  13. {
  14. _text.Append(' ', num);
  15. }
  16. private static void DoDump(object obj)
  17. {
  18. if (obj == null)
  19. {
  20. _text.Append("null");
  21. _text.Append(",");
  22. return;
  23. }
  24. Type t = obj.GetType();
  25. //repeat field
  26. if (obj is IList)
  27. {
  28. /*
  29. _text.Append(t.FullName);
  30. _text.Append(",");
  31. AppendIndent(1);
  32. */
  33. _text.Append("[");
  34. IList list = obj as IList;
  35. foreach (object v in list)
  36. {
  37. DoDump(v);
  38. }
  39. _text.Append("]");
  40. }
  41. else if (t.IsValueType)
  42. {
  43. _text.Append(obj);
  44. _text.Append(",");
  45. AppendIndent(1);
  46. }
  47. else if (obj is string)
  48. {
  49. _text.Append("\"");
  50. _text.Append(obj);
  51. _text.Append("\"");
  52. _text.Append(",");
  53. AppendIndent(1);
  54. }
  55. else if (obj is ByteString)
  56. {
  57. _text.Append("\"");
  58. _text.Append(((ByteString) obj).bytes.Utf8ToStr());
  59. _text.Append("\"");
  60. _text.Append(",");
  61. AppendIndent(1);
  62. }
  63. else if (t.IsArray)
  64. {
  65. Array a = (Array) obj;
  66. _text.Append("[");
  67. for (int i = 0; i < a.Length; i++)
  68. {
  69. _text.Append(i);
  70. _text.Append(":");
  71. DoDump(a.GetValue(i));
  72. }
  73. _text.Append("]");
  74. }
  75. else if (t.IsClass)
  76. {
  77. _text.Append($"<{t.Name}>");
  78. _text.Append("{");
  79. var fields = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  80. if (fields.Length > 0)
  81. {
  82. foreach (PropertyInfo info in fields)
  83. {
  84. _text.Append(info.Name);
  85. _text.Append(":");
  86. object value = info.GetGetMethod().Invoke(obj, null);
  87. DoDump(value);
  88. }
  89. }
  90. _text.Append("}");
  91. }
  92. else
  93. {
  94. Debug.LogWarning("unsupport type: " + t.FullName);
  95. _text.Append(obj);
  96. _text.Append(",");
  97. AppendIndent(1);
  98. }
  99. }
  100. public static string DumpAsString(object obj, string hint = "")
  101. {
  102. _text.Clear();
  103. _text.Append(hint);
  104. DoDump(obj);
  105. return _text.ToString();
  106. }
  107. }
  108. }