PIbd-23_Dolgova_D.N._Warmly.../WarmlyShip/Generics/SetGeneric.cs
2023-12-26 23:00:14 +04:00

135 lines
3.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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