115 lines
3.0 KiB
C#
115 lines
3.0 KiB
C#
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 T?[] _places;
|
||
|
||
/// <summary>
|
||
/// Количество объектов в массиве
|
||
/// </summary>
|
||
public int Count => _places.Length;
|
||
|
||
/// <summary>
|
||
/// Конструктор
|
||
/// </summary>
|
||
/// <param name="count"></param>
|
||
public SetGeneric(int count)
|
||
{
|
||
_places = new T?[count];
|
||
}
|
||
|
||
/// <summary>
|
||
/// Добавление объекта в набор
|
||
/// </summary>
|
||
/// <param name="ship">Добавляемый корабль</param>
|
||
/// <returns></returns>
|
||
public int Insert(T ship)
|
||
{
|
||
return Insert(ship, 0);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Добавление объекта в набор на конкретную позицию
|
||
/// </summary>
|
||
/// <param name="ship">Добавляемый корабль</param>
|
||
/// <param name="position">Позиция</param>
|
||
/// <returns></returns>
|
||
public int Insert(T ship, int position)
|
||
{
|
||
int nullIndex = -1, i;
|
||
|
||
if (position < 0 || position >= Count)
|
||
{
|
||
return -1;
|
||
}
|
||
|
||
for (i = position; i < Count; i++)
|
||
{
|
||
if (_places[i] == null)
|
||
{
|
||
nullIndex = i;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (nullIndex < 0)
|
||
{
|
||
return -1;
|
||
}
|
||
|
||
for (i = nullIndex; i > position; i--)
|
||
{
|
||
_places[i] = _places[i - 1];
|
||
}
|
||
|
||
_places[position] = ship;
|
||
return position;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Удаление объекта из набора с конкретной позиции
|
||
/// </summary>
|
||
/// <param name="position"></param>
|
||
/// <returns></returns>
|
||
public bool Remove(int position)
|
||
{
|
||
if (position < 0 || position >= Count)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
_places[position] = null;
|
||
return true;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Получение объекта из набора по позиции
|
||
/// </summary>
|
||
/// <param name="position"></param>
|
||
/// <returns></returns>
|
||
public T? Get(int position)
|
||
{
|
||
if (position < 0 || position >= Count)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
return _places[position];
|
||
}
|
||
}
|
||
}
|