PackableList.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System.Collections;
  2. using System.IO;
  3. namespace InABox.Core
  4. {
  5. public interface IPackableList : IPackable, IList
  6. {
  7. }
  8. public class PackableList<T> : ObservableList<T>, IPackableList where T : BaseObject, IPackable, new()
  9. {
  10. public void Pack(BinaryWriter writer)
  11. {
  12. writer.Write(Count);
  13. foreach (var item in this)
  14. item.Pack(writer);
  15. }
  16. public void Unpack(BinaryReader reader)
  17. {
  18. var iCount = reader.ReadInt32();
  19. for (var i = 0; i < iCount; i++)
  20. {
  21. var item = new T();
  22. item.Unpack(reader);
  23. Add(item);
  24. }
  25. }
  26. public override int GetHashCode()
  27. {
  28. return base.GetHashCode();
  29. }
  30. public override bool Equals(object obj)
  31. {
  32. var other = obj as PackableList<T>;
  33. if (other == null)
  34. return false;
  35. if (Count != other.Count) // Require equal count.
  36. return false;
  37. for (var i = 0; i < Count; i++)
  38. {
  39. var item1 = this[i];
  40. var item2 = other[i];
  41. if (item1 == null)
  42. {
  43. if (item2 != null)
  44. return false;
  45. }
  46. else if (!item1.Equals(item2))
  47. {
  48. return false;
  49. }
  50. }
  51. return true;
  52. }
  53. }
  54. }