126 lines
3.7 KiB
C#
126 lines
3.7 KiB
C#
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;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|