PIbd_23_Kislitsa_E.D_AirFig.../AirFighter/SetGeneric.cs
2023-12-08 21:44:38 +03:00

81 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectAirFighter.Exceptions;
using System.Windows.Forms;
namespace ProjectAirFighter.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 bool Insert(T airplane)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(airplane, 0);
return true;
}
public bool Insert(T airplane, int position)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false;
_places.Insert(position, airplane);
return true;
}
public bool Remove(int position)
{
if (!(position >= 0 && position < Count))
throw new AirplaneNotFoundException(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);
return;
}
}
public IEnumerable<T?> GetAirplanes(int? maxAirplanes = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxAirplanes.HasValue && i == maxAirplanes.Value)
{
yield break;
}
}
}
}
}