PIbd-22_Shabunov_O.A._AirBo.../AirBomber/Generics/SetGeneric.cs
2023-11-25 23:44:01 +04:00

94 lines
2.3 KiB
C#

using AirBomber.Exceptions;
namespace AirBomber.Generics
{
internal class SetGeneric<T>
where T : class
{
private readonly List<T?> _objects;
private readonly int _maxCount;
public int Count => _objects.Count;
public SetGeneric(int Count)
{
_maxCount = Count;
_objects = new List<T?>(_maxCount);
for (int i = 0; i < _maxCount; i++)
_objects.Add(null);
}
public int Insert(T Entity)
{
/** Вставка в начало набора */
for (int i = 0; i < _maxCount; i++)
if (_objects[i] is null)
{
_objects[i] = Entity;
return i;
}
throw new StorageOverflowException();
}
public int Insert(T Entity, int Position)
{
if (Position >= _maxCount)
throw new StorageOverflowException();
if (_objects[Position] is null)
{
_objects[Position] = Entity;
return Position;
}
throw new StorageOverflowException();
}
public bool Remove(int Position)
{
if (Position >= _maxCount)
throw new EntityNotFoundException();
if (_objects[Position] is null)
throw new EntityNotFoundException();
_objects[Position] = default(T);
return true;
}
public T? this[int Position]
{
get
{
if (Position >= _maxCount)
return null;
return _objects[Position];
}
set
{
if (Position >= _maxCount)
return;
if (_objects[Position] is not null)
return;
_objects[Position] = value;
}
}
public IEnumerable<T?> GetEntities(int? MaxEntities = null)
{
for (int i = 0; i < _objects.Count; ++i)
{
yield return _objects[i];
if (MaxEntities.HasValue && i == MaxEntities.Value)
yield break;
}
}
}
}