CSharpKeyValueTableGenerater.cs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. namespace etoy
  2. {
  3. class CSharpKeyValueTableGenerater : IGenerater
  4. {
  5. //private const string CLASS_TAIL = "Table"; // C# Table作为类型后缀
  6. public void Generate(Context context)
  7. {
  8. var tables = context.Blackboard.KeyValueTables;
  9. foreach (var table in tables)
  10. GenSingle(context, table);
  11. }
  12. void GenSingle(Context context, KeyValueTable table)
  13. {
  14. const string FIELD_REPEATED = "[]";
  15. string fileName = "KeyValue.cs";
  16. string directory = context.Option.ClientCodeOutput;
  17. string path = Path.Combine(directory, fileName);
  18. if (!Directory.Exists(directory))
  19. Directory.CreateDirectory(directory);
  20. using CodeWriter writer = new CodeWriter(path);
  21. writer.WriteLine("// Generate By EToy");
  22. writer.WriteLine("// Don't Edit It!!");
  23. writer.WriteLine();
  24. // namespace
  25. writer.Bracket("namespace XGame.Database");
  26. {
  27. // class
  28. writer.Bracket($"public static class KeyValue");
  29. {
  30. for (int i = 0, length = table.Rows.Length; i < length; i++)
  31. {
  32. var row = table.Rows[i];
  33. if (!row.IsClientField)
  34. continue;
  35. string summary = row.Description;
  36. string fieldType = row.Type;
  37. string fieldName = row.Key;
  38. string content = row.Value;
  39. // summary
  40. writer.Summary(summary);
  41. writer.Summary(content);
  42. // field
  43. var fieldValue = string.Empty;
  44. var repeadIdx = fieldType.IndexOf(FIELD_REPEATED);
  45. if (repeadIdx > 0)
  46. { // 是数组类型
  47. fieldValue = content.Replace("[", "{").Replace("]", "}");
  48. }
  49. else
  50. {
  51. switch (fieldType)
  52. {
  53. case FieldTypeDefine.Boolean:
  54. fieldValue = (content == "1" || content == "true") ? "true" : "false";
  55. break;
  56. case FieldTypeDefine.Int:
  57. fieldValue = content;
  58. break;
  59. case FieldTypeDefine.Long:
  60. fieldValue = content;
  61. break;
  62. case FieldTypeDefine.String:
  63. fieldValue = content.Replace("\"", "\\\""); // "前面多加个反斜杠
  64. fieldValue = $"\"{fieldValue}\"";
  65. break;
  66. default:
  67. throw new NotSupportedException($"KeyValue表C#代码生成失败, 不支持string/int外的类型{row.Type}字段。{table.Path}");
  68. }
  69. }
  70. writer.WriteLine($"public static readonly {fieldType} {fieldName} = {fieldValue};");
  71. // enter
  72. if (i < length - 1)
  73. writer.WriteLine();
  74. }
  75. writer.EndBracket();
  76. }
  77. writer.EndBracket();
  78. }
  79. }
  80. }
  81. }