using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; // Параметризованный набор объектов public class ListGenObj : ICollectionGenObj where T : class { // Список объектов, которые храним private List _collection; // Максимально допустимое число объектов в списке private int _maxCount; public int Count => _collection.Count; public int MaxCount { get { return _maxCount; } set { if (value > 0) { if (_collection.Count == 0) _collection = new List(value); else _collection.Capacity = value; // instead of resizing _maxCount = value; } } } public CollectionType GetCollectionType => CollectionType.List; public ListGenObj() { _collection = new(); } public T? GetItem(int position) { try { if (position > Count) throw new CollectionOverflowException(position); if (position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } catch (CollectionOverflowException ex) { Console.WriteLine(ex.Message); return null; } catch (ObjectNotFoundException ex) { Console.WriteLine(ex.Message); return null; } catch (PositionOutOfCollectionException ex) { Console.WriteLine(ex.Message); return null; } } public int Insert(T? obj) { if (obj == null) { return -1; } try // выход за границы, курируется CollectionOverflowException { if (Count >= _maxCount) { throw new CollectionOverflowException(Count); } _collection.Add(obj); return Count; } catch (CollectionOverflowException ex) { Console.WriteLine(ex.Message); return -1; } } public int Insert(T? obj, int position) { try { if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); if (Count >= _maxCount) throw new CollectionOverflowException(Count); if (obj == null) throw new ObjectNotFoundException(position); _collection.Insert(position, obj); return position; } catch (CollectionOverflowException ex) { Console.WriteLine(ex.Message); return -1; } catch (ObjectNotFoundException ex) { Console.WriteLine(ex.Message); return -1; } catch (PositionOutOfCollectionException ex) { Console.WriteLine(ex.Message); return -1; } } public T? Remove(int position) { try { if (position >= _maxCount || position < 0) // on the other positions items don't exist { throw new CollectionOverflowException(position); } T? item = _collection[position]; _collection.RemoveAt(position); if (item == null) throw new ObjectNotFoundException(position); return item; } catch (CollectionOverflowException ex) { Console.WriteLine(ex.Message); return null; } catch (ObjectNotFoundException ex) { Console.WriteLine(ex.Message); return null; } } public IEnumerable GetItems() { for (int i = 0; i < _collection.Count; ++i) { yield return _collection[i]; } } }