2023-02-08 23:32:38 +04:00

126 lines
3.7 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetWarmlyShipGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T> _places;
/// <summary>
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetWarmlyShipGeneric(int count)
{
_maxCount = count;
_places = new List<T>();
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="ship">Добавляемый корабль</param>
/// <returns></returns>
public int Insert(T ship)
{
if (Count < _maxCount)
return Insert(ship, 0);
return -1;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="ship">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T ship, int position)
{
if (Count >= _maxCount)
{
throw new StorageOverflowException(Count);
}
if (position < 0 || position > Count)
{
return -1;
}
_places.Insert(position, ship);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Remove(int position)
{
if (position < 0 || position >= Count)
return null;
var result = _places[position];
if (result == null)
{
throw new WarmlyShipNotFoundException(position);
}
_places.RemoveAt(position);
return result;
}
/// <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 >= _maxCount)
return;
_places.Add(value);
}
}
/// <summary>
/// Проход по набору до первого пустого
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetShip()
{
foreach (var ship in _places)
{
if (ship != null)
{
yield return ship;
}
else
{
yield break;
}
}
}
}
}