PopsicleList.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Collections;
  5. namespace Google.ProtocolBuffers.Collections {
  6. /// <summary>
  7. /// Proxies calls to a <see cref="List{T}" />, but allows the list
  8. /// to be made read-only (with the <see cref="MakeReadOnly" /> method),
  9. /// after which any modifying methods throw <see cref="NotSupportedException" />.
  10. /// </summary>
  11. public sealed class PopsicleList<T> : IList<T> {
  12. private readonly List<T> items = new List<T>();
  13. private bool readOnly = false;
  14. /// <summary>
  15. /// Makes this list read-only ("freezes the popsicle"). From this
  16. /// point on, mutating methods (Clear, Add etc) will throw a
  17. /// NotSupportedException. There is no way of "defrosting" the list afterwards.
  18. /// </summary>
  19. public void MakeReadOnly() {
  20. readOnly = true;
  21. }
  22. public int IndexOf(T item) {
  23. return items.IndexOf(item);
  24. }
  25. public void Insert(int index, T item) {
  26. ValidateModification();
  27. items.Insert(index, item);
  28. }
  29. public void RemoveAt(int index) {
  30. ValidateModification();
  31. items.RemoveAt(index);
  32. }
  33. public T this[int index] {
  34. get {
  35. return items[index];
  36. }
  37. set {
  38. ValidateModification();
  39. items[index] = value;
  40. }
  41. }
  42. public void Add(T item) {
  43. ValidateModification();
  44. items.Add(item);
  45. }
  46. public void Clear() {
  47. ValidateModification();
  48. items.Clear();
  49. }
  50. public bool Contains(T item) {
  51. return items.Contains(item);
  52. }
  53. public void CopyTo(T[] array, int arrayIndex) {
  54. items.CopyTo(array, arrayIndex);
  55. }
  56. public int Count {
  57. get { return items.Count; }
  58. }
  59. public bool IsReadOnly {
  60. get { return readOnly; }
  61. }
  62. public bool Remove(T item) {
  63. ValidateModification();
  64. return items.Remove(item);
  65. }
  66. public IEnumerator<T> GetEnumerator() {
  67. return items.GetEnumerator();
  68. }
  69. IEnumerator IEnumerable.GetEnumerator() {
  70. return GetEnumerator();
  71. }
  72. private void ValidateModification() {
  73. if (readOnly) {
  74. throw new NotSupportedException("List is read-only");
  75. }
  76. }
  77. }
  78. }