using ProjectBulldozer.Exceptions; namespace ProjectBulldozer.Generics { internal class SetGeneric where T : class { private readonly List _places; public int Count => _places.Count; /// Максимальное количество объектов в списке private readonly int _maxCount; public SetGeneric(int count) { _maxCount = count; _places = new List(count); } /// Добавление объекта в набор public int Insert(T tractor, IEqualityComparer? equal = null) { if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); Insert(tractor, 0, equal); return 0; } public bool Insert(T tractor, int position, IEqualityComparer? equal = null) { if (position < 0 || position >= _maxCount) { throw new BulldozerNotFoundException(position); } if (Count >= _maxCount) { throw new StorageOverflowException(_maxCount); } if (equal != null) { foreach (var i in _places) { if (equal.Equals(i, tractor)) { throw new ApplicationException($"Объект уже существует"); } } } _places.Insert(position, tractor); return true; } public bool Remove(int position) { if (position < 0 || position >= _maxCount) { return false; } if (_places[position] == null) { throw new BulldozerNotFoundException(position); } _places[position] = null; return true; } public T? this[int position] { get { if (position < 0 || position >= Count) return null; return _places[position]; } set { if (position < 0 || position >= Count || Count == _maxCount) return; _places.Insert(position, value); } } public IEnumerable GetTractors(int? maxTracts = null) { for (int i = 0; i < _places.Count; ++i) { yield return _places[i]; if (maxTracts.HasValue && i == maxTracts.Value) { yield break; } } } public void SortSet(IComparer comparer) => _places.Sort(comparer); } }