ReadOnlyInteropCollection.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace WinSCP
  5. {
  6. // Originally, the interop classes were each implemented separately. Probably because at the time they were
  7. // originally implemented, it was not possible to implement them via generic parent class.
  8. // Now it seems to work (something was improved in in .NET interop meanwhile?)
  9. //
  10. // Before reimplementing using this common parent class, the actual collection classes had to have ComDefaultInterface attribute.
  11. // Now it is not needed for some reason. Possibly the implicit default interface is picked rather randomly.
  12. // So we still keep the attribute, just in case.
  13. public class ReadOnlyInteropCollection<T> : ICollection<T>
  14. {
  15. internal ReadOnlyInteropCollection()
  16. {
  17. }
  18. public T this[int index]
  19. {
  20. get => _list[index];
  21. set => throw CreateReadOnlyException();
  22. }
  23. #region ICollection<T> Members
  24. public void Add(T item) => throw CreateReadOnlyException();
  25. public void Clear() => throw CreateReadOnlyException();
  26. public bool Contains(T item) => _list.Contains(item);
  27. public void CopyTo(T[] array, int arrayIndex)
  28. {
  29. _list.CopyTo(array, arrayIndex);
  30. }
  31. public int Count => _list.Count;
  32. public bool IsReadOnly => true;
  33. public bool Remove(T item)
  34. {
  35. throw CreateReadOnlyException();
  36. }
  37. #endregion
  38. #region IEnumerable<T> Members
  39. public IEnumerator<T> GetEnumerator() => _list.GetEnumerator();
  40. #endregion
  41. #region IEnumerable Members
  42. IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator();
  43. #endregion
  44. internal void InternalAdd(T item)
  45. {
  46. _list.Add(item);
  47. }
  48. internal void InternalRemoveFirst()
  49. {
  50. _list.RemoveAt(0);
  51. }
  52. private static Exception CreateReadOnlyException() => new InvalidOperationException("Collection is read-only.");
  53. private readonly List<T> _list = new List<T>();
  54. }
  55. }