diff --git a/ProjectStormtrooper/ProjectStormtrooper/SetGeneric.cs b/ProjectStormtrooper/ProjectStormtrooper/SetGeneric.cs index 7e6cfab..51f90cd 100644 --- a/ProjectStormtrooper/ProjectStormtrooper/SetGeneric.cs +++ b/ProjectStormtrooper/ProjectStormtrooper/SetGeneric.cs @@ -12,20 +12,25 @@ namespace ProjectStormtrooper internal class SetGeneric where T : class { /// - /// Массив объектов, которые храним + /// Список объектов, которые храним /// - private readonly T?[] _places; + private readonly List _places; /// /// Количество объектов в массиве /// - public int Count => _places.Length; + public int Count => _places.Count; + /// + /// Максимальное количество объектов в списке + /// + private readonly int _maxCount; /// /// Конструктор /// /// public SetGeneric(int count) { - _places = new T?[count]; + _maxCount = count; + _places = new List(count); } /// /// Добавления объекта в набор @@ -45,38 +50,12 @@ namespace ProjectStormtrooper public int Insert(T plane, int position) { // Проверка позиции - if (position < 0 || position >= Count) + if (position < 0 || position >= _maxCount) { return -1; } - // Проверка, что элемент массива по этой позиции пустой - if (_places[position] != null) - { - // Проверка, что после вставляемого элемента в массиве есть пустой элемент - int nullIndex = -1; - for (int i = position + 1; i < Count; i++) - { - if (_places[i] == null) - { - nullIndex = i; - break; - } - } - // Если пустого элемента нет, то выходим - if (nullIndex < 0) - { - return -1; - } - // Сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента - int j = nullIndex - 1; - while (j >= position) - { - _places[j + 1] = _places[j]; - j--; - } - } // Вставка по позиции - _places[position] = plane; + _places.Insert(position, plane); return position; } /// @@ -87,7 +66,7 @@ namespace ProjectStormtrooper public T? Remove(int position) { // Проверка позиции - if (position < 0 || position >= Count) + if (Count == 0 || position < 0 || position >= _maxCount) { return null; } @@ -101,14 +80,43 @@ namespace ProjectStormtrooper /// /// /// - public T? Get(int position) + public T? this[int position] { - // Проверка позиции - if (position < 0 || position >= Count) + get { - return null; + // Проверка позиции + if (position < 0 || position >= _maxCount) + { + return null; + } + return _places[position]; + } + set + { + // Проверка позиции + // Проверка свободных мест в списке + if (position < 0 || position >= _maxCount || Count == _maxCount) + { + return; + } + // Вставка в список по позиции + _places.Insert(position, value); + } + } + /// + /// Проход по списку + /// + /// + public IEnumerable GetPlanes(int? maxPlanes = null) + { + for (int i = 0; i < _places.Count; ++i) + { + yield return _places[i]; + if (maxPlanes.HasValue && i == maxPlanes.Value) + { + yield break; + } } - return _places[position]; } } }