TableRepository.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using XGame.Framework.Asyncs;
  4. using XGame.Framework.Serialization;
  5. namespace XGame.Framework.Database
  6. {
  7. public abstract class TableRepository<TTable, TRepository> : ISerializable, IDisposable where TTable : class, ITable where TRepository : TableRepository<TTable, TRepository>
  8. {
  9. protected TTable[] _tables;
  10. protected Dictionary<long, TTable> _tableMap;
  11. void ISerializable.Deserialize(IReader reader)
  12. {
  13. _tables = reader.ReadEnumerable<TTable[]>();
  14. _tableMap = new Dictionary<long, TTable>();
  15. foreach(var table in _tables)
  16. {
  17. #if UNITY_EDITOR
  18. if (_tableMap.ContainsKey(table.Key))
  19. {
  20. Log.Error($"TableRepository 重复数据. Name:{typeof(TTable)} Id:{table.Key}");
  21. continue;
  22. }
  23. #endif
  24. _tableMap.Add(table.Key, table);
  25. }
  26. }
  27. void ISerializable.Serialize(IWriter writer)
  28. {
  29. writer.Write(_tables);
  30. }
  31. void IDisposable.Dispose()
  32. {
  33. _tables = null;
  34. _tableMap?.Clear();
  35. _tableMap = null;
  36. }
  37. public TTable GetByKey(long key)
  38. {
  39. if (_tableMap == null)
  40. {
  41. return default;
  42. }
  43. _tableMap.TryGetValue(key, out var table);
  44. return table;
  45. }
  46. public TTable[] GetAllTables()
  47. {
  48. if (_tables == null)
  49. {
  50. return default;
  51. }
  52. return _tables;
  53. }
  54. #region 静态方法
  55. public static string TableName => typeof(TTable).Name;
  56. public static TTable Get(long key)
  57. {
  58. return DatabaseModule.Instance.GetByKey<TTable, TRepository>(key);
  59. }
  60. public static TTable[] GetAll()
  61. {
  62. return DatabaseModule.Instance.GetAll<TTable, TRepository>();
  63. }
  64. public static IAsync LoadAsync()
  65. {
  66. return DatabaseModule.Instance.LoadAsync<TTable, TRepository>(TableName);
  67. }
  68. public static void Unload()
  69. {
  70. DatabaseModule.Instance.Unload(TableName);
  71. }
  72. //public static implicit operator TableRepository<TTable>(TableRepository<ITable> v)
  73. //{
  74. // return v as TableRepository<TTable>;
  75. //}
  76. #endregion
  77. }
  78. }