Dumper.cs 3.2 KB

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