using WarmlyShip.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WarmlyShip.Generics { /// /// Параметризованный набор объектов /// /// internal class SetGeneric where T : class { /// /// Список объектов, которые храним /// private readonly List _places; /// /// Количество объектов в списке /// public int Count => _places.Count; /// /// Максимальное количество объектов в cписке /// private readonly int _maxCount; //// /// Конструктор /// /// public SetGeneric(int count) { _maxCount = count; _places = new List(count); } /// /// Добавление объекта в набор /// /// Добавляемый корабль /// public void Insert(T ship) { if (_places.Count == _maxCount) { throw new StorageOverflowException(_maxCount); } Insert(ship, 0); } /// /// Добавление объекта в набор на конкретную позицию /// /// Добавляемый корабль /// Позиция /// public void Insert(T ship, int position) { if (_places.Count == _maxCount) { throw new StorageOverflowException(_maxCount); } if (!(position >= 0 && position <= Count)) { throw new Exception("Неверная позиция для вставки"); } _places.Insert(position, ship); } /// /// Удаление объекта из набора с конкретной позиции /// /// /// public void Remove(int position) { if (!(position >= 0 && position < Count)) { throw new ShipNotFoundException(position); } _places.RemoveAt(position); } /// /// Получение объекта из набора по позиции /// /// /// public T? this[int position] { get { if (!(position >= 0 && position < Count)) { return null; } return _places[position]; } set { if (!(position >= 0 && position < Count && _places.Count < _maxCount)) { return; } _places.Insert(position, value); } } /// /// Проход по списку /// /// public IEnumerable GetShips(int? maxShips = null) { for (int i = 0; i < _places.Count; ++i) { yield return _places[i]; if (maxShips.HasValue && i == maxShips.Value) { yield break; } } } } }