using ProjectCruiser.DrawningSamples; 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) { if (position > _maxCount) throw new CollectionOverflowException(position); if (position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T? obj, IEqualityComparer? cmpr = null) { if (obj == null) throw new NullReferenceException("> Inserting object is null"); else { if (cmpr != null && obj == cmpr) { throw new Exception(); } } // выход за границы, курируется CollectionOverflowException if (Count >= _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T? obj, int position, IEqualityComparer? cmpr = null) { if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); if (Count >= _maxCount) throw new CollectionOverflowException(Count); if (obj == null) throw new NullReferenceException("> Inserting object (at position) is null"); else { if (cmpr != null && obj == cmpr) { throw new Exception(); } } _collection.Insert(position, obj); return position; } public T? Remove(int position) { if (position >= _maxCount || position < 0) // on the other positions items don't exist { throw new PositionOutOfCollectionException(position); } T? item = _collection[position]; _collection.RemoveAt(position); if (item == null) throw new ObjectNotFoundException(position); return item; } public IEnumerable GetItems() { for (int i = 0; i < _collection.Count; ++i) { yield return _collection[i]; } } void ICollectionGenObj.CollectionSort(IComparer comparer) { _collection.Sort(comparer); } }