Александр Чегодаев ce4dd23448 lab7
2023-12-22 17:38:52 +04:00

105 lines
2.7 KiB
C#

using Cruiser;
using Cruiser.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCruiser.Generics
{
internal class SetGeneric<T>
where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
public int Insert(T cruiser)
{
if (_places.Count == 0)
{
_places.Add(cruiser);
return 0;
}
else
{
if (_places.Count < _maxCount)
{
_places.Add(cruiser);
for (int i = 0; i < _places.Count; i++)
{
T temp = _places[i];
_places[i] = _places[_places.Count - 1];
_places[_places.Count - 1] = temp;
}
return 0;
}
else
{
throw new StorageOverflowException(_places.Count);
}
}
}
public bool Insert(T cruiser, int position)
{
if (position < 0 || position >= _maxCount)
throw new CruiserNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(position);
_places.Insert(0, cruiser);
return true;
}
public bool Remove(int position)
{
if (position < 0 || position > _maxCount || position >= Count)
throw new CruiserNotFoundException();
if (_places[position] == null)
{
throw new CruiserNotFoundException();
}
_places[position] = null;
return true;
}
public T? this[int position]
{
get
{
if (position < 0 || position > _maxCount)
return null;
return _places[position];
}
set
{
if (position < 0 || position > _maxCount)
return;
_places[position] = value;
}
}
public IEnumerable<T?> GetCruiser(int? maxCruiser = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxCruiser.HasValue && i == maxCruiser.Value)
{
yield break;
}
}
}
}
}