2024-10-08 12:32:16 +04:00

111 lines
3.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.Exceptions;
namespace Tank.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount
{
get
{
return _collection.Count;
}
set
{
if (value > 0)
{
_maxCount = value - 1;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
//TODO проверка позиции
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
//TODO вставка в конец набора
_collection.Add(obj);
return _collection.Count;
}
public int Insert(T obj, int position)
{
//TODO проверка что не превышено максимальное кол-во элементов
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
// TODO проверка позиции
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
// TODO вставка по позиции
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
// TODO удаление объекта из списка
T? obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}