100 lines
2.8 KiB
C#
Raw Normal View History

2023-12-22 19:20:28 +04:00
using ProjectLainer.DrawningObjects;
using ProjectLainer.Exceptions;
2023-12-21 21:21:02 +04:00
using System.Numerics;
2023-12-19 18:48:02 +04:00
namespace ProjectLainer.Generics
2023-12-08 21:11:13 +04:00
{
internal class SetGeneric<T>
where T : class
{
2023-12-19 18:48:02 +04:00
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
2023-12-08 21:11:13 +04:00
public SetGeneric(int count)
{
2023-12-19 18:48:02 +04:00
_maxCount = count;
_places = new List<T?>(count);
2023-12-08 21:11:13 +04:00
}
2023-12-22 19:20:28 +04:00
public bool Insert(T lainer, IEqualityComparer<T?>? equal = null)
2023-12-08 21:11:13 +04:00
{
2023-12-19 18:48:02 +04:00
if (_places.Count == _maxCount)
2023-12-08 21:11:13 +04:00
{
2023-12-22 19:20:28 +04:00
throw new OverflowException();
2023-12-08 21:11:13 +04:00
}
2023-12-22 19:20:28 +04:00
Insert(lainer, 0, equal);
return true;
2023-12-08 21:11:13 +04:00
}
2023-12-22 19:20:28 +04:00
public bool Insert(T lainer, int position, IEqualityComparer<T?>? equal = null)
2023-12-08 21:11:13 +04:00
{
2023-12-22 19:20:28 +04:00
// объект есть уже в коллекции - выбросить исключение
if (!(position >= 0 && position <= Count))
2023-12-08 21:11:13 +04:00
{
2023-12-22 19:20:28 +04:00
return false;
2023-12-21 21:21:02 +04:00
}
2023-12-22 19:20:28 +04:00
if (equal != null)
2023-12-21 21:21:02 +04:00
{
2023-12-22 19:20:28 +04:00
foreach (T elem in _places)
{
if (equal.Equals(lainer, elem))
{
throw new Exception("такой объект уже есть");
}
}
2023-12-08 21:11:13 +04:00
}
2023-12-22 19:20:28 +04:00
_places.Insert(position, lainer);
return true;
2023-12-19 18:48:02 +04:00
}
2023-12-21 21:21:02 +04:00
2023-12-22 19:20:28 +04:00
public bool Remove(int position)
2023-12-19 18:48:02 +04:00
{
2023-12-22 19:20:28 +04:00
if(position < _maxCount && position >= 0)
2023-12-08 21:11:13 +04:00
{
2023-12-22 19:20:28 +04:00
if(position < Count)
{
_places.RemoveAt(position);
return true;
}
else
{
throw new LainerNotFoundException();
}
2023-12-08 21:11:13 +04:00
}
2023-12-22 19:20:28 +04:00
return false;
2023-12-08 21:11:13 +04:00
}
2023-12-19 18:48:02 +04:00
public T? this[int position]
2023-12-08 21:11:13 +04:00
{
2023-12-19 18:48:02 +04:00
get
{
if(position < 0 || position >= Count)
{
return null;
}
2023-12-08 21:11:13 +04:00
return _places[position];
}
2023-12-19 18:48:02 +04:00
set
{
if (position < 0 || position >= Count || Count >= _maxCount)
{
return;
}
_places.Insert(position, value);
}
}
public IEnumerable<T?> GetLainers(int? maxLainers = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxLainers.HasValue && i == maxLainers.Value)
{
yield break;
}
}
2023-12-08 21:11:13 +04:00
}
2023-12-22 19:20:28 +04:00
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
2023-12-08 21:11:13 +04:00
}
}