StorableFixedArray.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. namespace Island.StandardLib.Storage
  7. {
  8. /// <summary>
  9. /// 表示一个每项长度固定的可序列化变长数组(固定项长可变数组)
  10. /// </summary>
  11. /// <typeparam name="T">定长项的类型</typeparam>
  12. [Serializable]
  13. public class StorableFixedArray<T> : IStorable, IEnumerable<T> where T : IStorable, new()
  14. {
  15. List<T> array;
  16. /// <summary>
  17. /// 初始化固定项长可变数组
  18. /// </summary>
  19. public StorableFixedArray()
  20. {
  21. array = new List<T>();
  22. }
  23. public void ReadFromData(DataStorage data)
  24. {
  25. data.Read(out int size);
  26. for (int i = 0; i < size; i++)
  27. array.Add(data.Read<T>());
  28. }
  29. public void WriteToData(DataStorage data)
  30. {
  31. data.Write(array.Count);
  32. for (int i = 0; i < array.Count; i++)
  33. data.Write(array[i]);
  34. }
  35. public void Add(T item)
  36. {
  37. array.Add(item);
  38. }
  39. public void AddRange(IEnumerable<T> item)
  40. {
  41. array.AddRange(item);
  42. }
  43. public void Remove(T item)
  44. {
  45. array.Remove(item);
  46. }
  47. public void RemoveAt(int index)
  48. {
  49. array.RemoveAt(index);
  50. }
  51. public void Clear()
  52. {
  53. array.Clear();
  54. }
  55. public IEnumerator<T> GetEnumerator()
  56. {
  57. List<T> tl = new List<T>();
  58. for (int i = 0; i < array.Count; i++)
  59. tl.Add(array[i]);
  60. return tl.GetEnumerator();
  61. }
  62. IEnumerator IEnumerable.GetEnumerator()
  63. {
  64. List<T> tl = new List<T>();
  65. for (int i = 0; i < array.Count; i++)
  66. tl.Add(array[i]);
  67. return tl.GetEnumerator();
  68. }
  69. public int Count
  70. {
  71. get
  72. {
  73. return array.Count;
  74. }
  75. }
  76. public int Size
  77. {
  78. get
  79. {
  80. return array.Count;
  81. }
  82. }
  83. public int Length
  84. {
  85. get
  86. {
  87. return array.Count;
  88. }
  89. }
  90. public T this[int index]
  91. {
  92. get
  93. {
  94. return array[index];
  95. }
  96. }
  97. }
  98. }