2023-12-16 23:50:00 +04:00

107 lines
3.6 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 ProjectTank.Exceptions;
namespace ProjectTank.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>
/// Конструктор
/// </summary>
/// <param name="count"></param>
private readonly int _maxCount;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="tank">Добавляемый танк</param>
/// <returns></returns>
public bool Insert(T tank, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(tank, 0, equal);
return true;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="tank">Добавляемый танк</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T tank, int position, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false;
if (equal != null)
{
if (_places.Contains(tank, equal))
throw new ArgumentException(nameof(tank));
}
_places.Insert(position, tank);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (!(position >= 0 && position < Count))
throw new TankNotFoundException(position);
_places.RemoveAt(position);
return true;
}
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>
/// <param name="position"></param>
/// <returns></returns>
public IEnumerable<T?> GetTanks(int? maxTanks = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxTanks.HasValue && i == maxTanks.Value)
{
yield break;
}
}
}
}
}