ReadOnlyDictionary.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using IEnumerable=System.Collections.IEnumerable;
  6. namespace Google.ProtocolBuffers.Collections {
  7. /// <summary>
  8. /// Read-only wrapper around another dictionary.
  9. /// </summary>
  10. public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
  11. readonly IDictionary<TKey, TValue> wrapped;
  12. public ReadOnlyDictionary(IDictionary<TKey, TValue> wrapped) {
  13. this.wrapped = wrapped;
  14. }
  15. public void Add(TKey key, TValue value) {
  16. throw new InvalidOperationException();
  17. }
  18. public bool ContainsKey(TKey key) {
  19. return wrapped.ContainsKey(key);
  20. }
  21. public ICollection<TKey> Keys {
  22. get { return wrapped.Keys; }
  23. }
  24. public bool Remove(TKey key) {
  25. throw new InvalidOperationException();
  26. }
  27. public bool TryGetValue(TKey key, out TValue value) {
  28. return wrapped.TryGetValue(key, out value);
  29. }
  30. public ICollection<TValue> Values {
  31. get { return wrapped.Values; }
  32. }
  33. public TValue this[TKey key] {
  34. get {
  35. return wrapped[key];
  36. }
  37. set {
  38. throw new InvalidOperationException();
  39. }
  40. }
  41. public void Add(KeyValuePair<TKey, TValue> item) {
  42. throw new InvalidOperationException();
  43. }
  44. public void Clear() {
  45. throw new InvalidOperationException();
  46. }
  47. public bool Contains(KeyValuePair<TKey, TValue> item) {
  48. return wrapped.Contains(item);
  49. }
  50. public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
  51. wrapped.CopyTo(array, arrayIndex);
  52. }
  53. public int Count {
  54. get { return wrapped.Count; }
  55. }
  56. public bool IsReadOnly {
  57. get { return true; }
  58. }
  59. public bool Remove(KeyValuePair<TKey, TValue> item) {
  60. throw new InvalidOperationException();
  61. }
  62. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
  63. return wrapped.GetEnumerator();
  64. }
  65. IEnumerator IEnumerable.GetEnumerator() {
  66. return ((IEnumerable) wrapped).GetEnumerator();
  67. }
  68. public override bool Equals(object obj) {
  69. return wrapped.Equals(obj);
  70. }
  71. public override int GetHashCode() {
  72. return wrapped.GetHashCode();
  73. }
  74. public override string ToString() {
  75. return wrapped.ToString();
  76. }
  77. }
  78. }